Configure logging in .NET Core 3 with NLog

Configuring NLog Logging in a .NET Core 3.1 Worker Service Application

I’m using NLog in a .NET Core 3.1 worker service application and have configured it with an nlog.config file. However, I have three points where I can configure the logging:

  1. In the code where I need to create a logger in a dependency injection context:
// Other code...

services.AddScoped<IApplyJcdsCommandsJob, ApplyJcdsCommandsJob>(provider =>
{
    var loggerFactory = LoggerFactory.Create(builder =>
    {
        builder
            .ClearProviders()
            .AddFilter("Microsoft", Microsoft.Extensions.Logging.LogLevel.Trace)
            .AddFilter("System", Microsoft.Extensions.Logging.LogLevel.Trace)
            .AddFilter("ApplyJcdsCommandsJob", Microsoft.Extensions.Logging.LogLevel.Trace)
            //.AddConsole()
            //.AddEventLog();
            .AddNLog(configuration);
    });

    Microsoft.Extensions.Logging.ILogger logger = loggerFactory.CreateLogger<CommandsJob>();

    return new CommandsJob(logger);
})

// Other code...
  1. In appSettings.json:
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Trace",
      "System": "Trace",
      "Microsoft": "Trace"
    }
  }
}
  1. In NLog.config:
<!-- a section of the config -->
<targets>
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
        layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>

<rules>
    <logger name="*" minlevel="Trace" writeTo="f" />
</rules>
<!-- ... -->

I’m confused because if I remove the Nlog.config file, the log file will not be created, and other changes seem to have no effect. How are these configurations related? What is the best way to switch logging on/off and set the logging level?