1

I am trying to write logs using ILogger from Microsoft.Extensions.Logging and with NLog as a provider. I added a separate nlogsettings.json file to define configuration because to maintain appsettings file as minimum as possible and also to separate the config files during deployments to higher environments.

Here is my nlosettings.json where all my nlog configuration setup is defined.

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "NLog": {
        "internalLogFile": "c:\\Logs\\internal-nlog.txt",
        "LogLevel": {
          "Default": "Info",
          "Microsoft": "Warn",
          "Microsoft.Hosting.Lifetime": "Information"
        },
        "extensions": [
          { "assembly": "NLog.Extensions.Logging" },
          { "assembly": "NLog.Web.AspNetCore" }
        ],    
        "Targets": {
          "File": {
            "Type": "File",
            "FileName": "c:\\Logs\\service.log",
            "Layout": "${message}"
          }
        },
        "Rules": [
          {
            "Logger": "*",
            "MinLevel": "Debug",
            "WriteTo": "File"
          }
        ]
      }
    }

Here is my Program.cs which is the main entry

    public class Program
        {
        public static void Main(string[] args)
        {
           var logger = LogManager.Setup().LoadConfigurationFromFile("nlogsettings.json").GetCurrentClassLogger();
            logger.Info("Application starts");
            CreateHostBuilder(args).Build().Run();           
        }
    
        private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            }).ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            }).UseNLog();
    }

Here is my Controller . it is not a fancy controller. Just a GET method is returning OK with a message

public class InventoryController : ControllerBase
{
    private readonly ILogger<InventoryController> _logger;        
    public InventoryController(ILogger<InventoryController> logger, ILoggerFactory loggerFactory){_logger = logger;}
    [HttpGet]    
    public async Task<ActionResult> GetInventory()
    {
        await Task.Delay(100);            
        _logger.LogInformation("Testing the nlog log write");
        return Ok("Success");
    }
}

But when I debug it is hitting the breakpoint at logger.LogInformation but is not writing to the folder that is specified in nlogsettings.json. I tried different ways changing nlogsettings file. Can someone check and see if I am missing anything in the above set up?

1 Answer 1

1

LogManager.Setup().LoadConfigurationFromFile only supports XML-files, and not JSON-files. It is always a good idea to enable NLog InternalLogger when troubleshooting NLog.

If you install NLog.Extensions.Logging-nuget-package, then you can do this:

var config = new ConfigurationBuilder()
                .SetBasePath(basePath ?? Directory.GetCurrentDirectory())
                .AddJsonFile("nlogsettings.json", optional: false, reloadOnChange: true)
                .Build();
var logger = LogManager.Setup()
                       .LoadConfigurationFromSection(config)
                       .GetCurrentClassLogger();

See also https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-configuration-with-appsettings.json

Sign up to request clarification or add additional context in comments.

1 Comment

This is charm!! I have been struggling with 'LoadConfigurationFromFile' and was thinking it woks for all type of files. Thank you so much for your response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.