NLog configuration in appsettings.json instead of nlog.config in .NET Core

Yes, this is possible but has a minimum version requirement. You must be using NLog.Extensions.Logging >= 1.5.0. Note that for ASP.NET Core applications this will be installed as a dependency if you install NLog.Web.AspNetCore >= 4.8.2.

You can then create an NLog section in appsettings.json and load it with the following code:

var config = new ConfigurationBuilder()
  .SetBasePath(System.IO.Directory.GetCurrentDirectory())
  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
NLog.Config.LoggingConfiguration nlogConfig = new NLogLoggingConfiguration(config.GetSection("NLog"));

For example, for an ASP.NET Core application, your Main() method in Program.cs should look something like this:

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(System.IO.Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
    LogManager.Configuration = new NLogLoggingConfiguration(config.GetSection("NLog"));

    var logger = NLog.Web.NLogBuilder.ConfigureNLog(LogManager.Configuration).GetCurrentClassLogger();
    try
    {
        logger.Debug("Init main");
        CreateWebHostBuilder(args).Build().Run();
    }
    catch (Exception ex)
    {
        logger.Error(ex, "Stopped program because of exception");
    }
    finally {
        LogManager.Shutdown();
    }
}

A configuration like the one in the question can be achieved with the following settings in appsettings.json:

"NLog":{
    "internalLogLevel":"Info",
    "internalLogFile":"c:\\temp\\internal-nlog.txt",
    "extensions": [
      { "assembly": "NLog.Extensions.Logging" },
      { "assembly": "NLog.Web.AspNetCore" }
    ],
    "targets":{
        "allfile":{
            "type":"File",
            "fileName":"c:\\temp\\nlog-all-${shortdate}.log",
            "layout":"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"
        },
        "ownFile-web":{
            "type":"File",
            "fileName":"c:\\temp\\nlog-own-${shortdate}.log",
            "layout":"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}"
        }
    },
    "rules":[
        {
            "logger":"*",
            "minLevel":"Trace",
            "writeTo":"allfile"
        },
        {
            "logger":"Microsoft.*",
            "maxLevel":"Info",
            "final":"true"
        },
        {
            "logger":"*",
            "minLevel":"Trace",
            "writeTo":"ownFile-web"
        }
    ]
}

Edit: Thanks to Rolf Kristensen (who developed this functionality for NLog in the first place!) for pointing out this wiki page with more documentation on this feature: https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-configuration-with-appsettings.json

Leave a Comment