11

I'm using NLog in a .NET Core 3.1 worker service application. Following the tutorial of NLog I inserted an nlog.config file to manage the configuration.

Now I'm confused because I have three points where I 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...
    
  2. In appSettings.json

    {
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Trace",
          "System": "Trace",
          "Microsoft": "Trace"
        }
      }
    }
    
  3. In NLog.config

    The default config file produced by the nuget package installation:

    <!-- 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>
    <!-- ... -->
    

What I see is that if I remove the Nlog.config file, the log file will not be created. Other changes seam to have no effect.

How are this configurations related? What is the best way to switch on/off the logging and set the level?

Pang
  • 9,564
  • 146
  • 81
  • 122
Tonyc
  • 709
  • 1
  • 10
  • 29

2 Answers2

10

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

Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70
  • Based on the code-sample that you posted here: https://github.com/NLog/NLog.Extensions.Logging/issues/389 – Rolf Kristensen Jan 16 '20 at 20:29
  • It works using the AddConfiguration(). I found useful your update in the tutorial (do not use the Nuget Package NLog.Config in :NET Core projects). [NLog Install](https://github.com/nlog/nlog/wiki/NLog-Install) – Tonyc Jan 17 '20 at 09:28
  • It seems this solution is required also when using `appsettings.json` and `LogManager.Setup().LoadConfigurationFromAppSettings()` for configuration instead of `nlog.config`. Certainly in .NET 5, anyway. – Neo Nov 07 '20 at 18:14
  • @Neo Yes `LoadConfigurationFromAppSettings` does not register NLog as MEL LoggingProvider. But it allows you to load NLog-config from `appsettings.json` before having created HostBuilder. – Rolf Kristensen Nov 07 '20 at 20:25
7

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. Changed with NLog v5 that now ignores MEL filters by default.

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.

Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70
  • Hello. I tried to check what I understood implementing the console app in the example link you gave me. In addition, I added an appSettings.json file readind it with .AddJsonFile("appsettings.json"). In this case, should I expect that a log is filtered by the chain: SetMinimumLevel() -> appSettings.json -> NLog.config ? In my case appSettings.json seems to have no effect. So I only used "SetMinimumLevel" in the code and "NLog.config". – Tonyc Jan 15 '20 at 15:43
  • For example with the configuration (code, appsettings.json, NLog.config): `loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information); "Logging": { "LogLevel": {"Default": "Warning" }} ` I got the log `2020-01-15 16:45:03.3071 INFO Doing hard work! Action1 2020-01-15 16:45:03.3472 WARN Doing hard work! Action1 2020-01-15 16:45:03.3483 ERROR Doing hard work! Action1 2020-01-15 16:45:03.3483 FATAL Doing hard work! Action1` So, the appsettings.json config does nothing in the chain. – Tonyc Jan 15 '20 at 15:55
  • 1
    @Tonyc Think you have to create an issue at github: https://github.com/NLog/NLog.Extensions.Logging/issues/new and attach solution as zip-file. – Rolf Kristensen Jan 15 '20 at 20:09
  • Have replied to your issue: https://github.com/NLog/NLog.Extensions.Logging/issues/389 (Question and answer is not really related to NLog, but about MEL) – Rolf Kristensen Jan 16 '20 at 20:28