Manage logging configuration with NLog in .NET Core 3

AddNLog registers NLog like any other Microsoft Extension Logger (MEL) LoggingProvider (Similar to AddConsole).

This means NLog only gets log-output that has been "approved" by the MEL-ILogger. So any filtering configured in MEL will prevent logevents from reaching NLog.

NLog still has the ability to redirect based on Logger-names and LogLevel-severity to the wanted NLog-targets.

You can decide if you want to use MEL-Filtering or NLog-Filtering, or a combination of both. But if you just want to use "pure" NLog then just create an instance of NLog.Extensions.Logging.NLogLoggerFactory. It is a specialized ILoggerFactory that ignores MEL-Filtering-Configuration.

Btw. it is a little weird that you create an isolated LoggerFactory for each CommandsJob-instance. Would think that you would register the type in the dependency injection-framework, and let it inject constructor-parameters. See also this example:

https://github.com/NLog/NLog.Extensions.Logging/blob/master/examples/NetCore2/ConsoleExample/Program.cs

Where LoggerFactory is created with AddLogging(...) and where the Runner is registered in ServiceCollection for dependency-injection. When creating instance of Runner then dependency-injection will automatically provide ILogger as constructor-parameter.


People that decide to use NLog usually also want to disable all MEL-filtering to avoid the confusion with two filtering systems. So the NLog wiki-tutorial is targeted those users.

I guess people who are MEL-users first will probably just use new HostBuilder().CreateDefaultBuilder().Build() (Will setup everything with all guns enabled).

But if staying with the simple example, then you need to remove:

loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);

And add:

loggingBuilder.AddConfiguration(config.GetSection("Logging"));

So it looks like this:

serviceCollection.AddLogging(loggingBuilder =>
{
   loggingBuilder.ClearProviders();
   loggingBuilder.AddConfiguration(config.GetSection("Logging"));
   loggingBuilder.AddNLog(config);
})

ILoggingBuilder.AddConfiguration can be found at Nuget: Microsoft.Extensions.Logging.Configuration