davewilliams459
davewilliams459

Reputation: 1739

NLog Configuration specifically for .net core 3.1 specifying the nlog file by name/env, and enabling DI

How can I configure an asp.net core 3.1 application to use NLog, specifically setting a custom log filename (i.e. nlog.[environment].config, and also enable for DI. I have tried many things without success.

I know there are a lot SO questions and online articles about nlog configuration, but I cannot seem to find an example for my specific scenario and requirements. I am open to using altermative methods such as configuring via appsettings.[env].json, but want to avoid multiple web.config files

One example of what I have tried:

public static void Main(string[] args)
{
    var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");   

    var logFile = "nlog.config";
    if (environment.Contains("Debug") || environment.Contains("Local"))
        logFile = "nlog.debug.config";

    // logger works only in Main() method, not as DI
    var logger = NLogBuilder.ConfigureNLog(logFile).GetCurrentClassLogger();

    logger.Info("Starting My App");
    CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration((hostingContext, config) =>
    {
        config.Sources.Clear();

        var env = hostingContext.HostingEnvironment;

        config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json",
                            optional: true, reloadOnChange: true);

        config.AddEnvironmentVariables();

        if (args != null)
        {
            config.AddCommandLine(args);
        }
    })
    ... 
    .ConfigureLogging((hostingContext, logging) =>
    {
        logging.ClearProviders();
        logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug);
        logging.AddConsole();
    })
    .UseNLog(config); // << config has error, I can't seem to find a way to instanciate config. 
}

Upvotes: 2

Views: 3876

Answers (2)

Rolf Kristensen
Rolf Kristensen

Reputation: 19867

You can also consider placing environment-specific settings in the default appsettings.json and override with appsettings.[environment].json. Then just use ${configsetting} in NLog.config to load active setttings.

Works best if you use this:

var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Info("Starting My App");

And no longer use this:

var logger = NLogBuilder.ConfigureNLog(logFile).GetCurrentClassLogger();
logger.Info("Starting My App");

See also: https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3

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

Upvotes: 4

It's a little tricky. I have two NLog config files besides my main NLog config file. Those files are nlog.Production.config and nlog.NonProduction.config. In the main NLog file I'm using this line:

<include file="nlog.${when:when='${environment:ASPNETCORE_ENVIRONMENT}'=='Production':inner=Production:else=NonProduction}.config" />

Depending on the environment, one of those files is included.

See also: https://github.com/NLog/NLog/wiki/XML-config-include-Example

Upvotes: 3

Related Questions