Manage logging configuration with NLog in .NET Core 3

13,791

Solution 1

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

Solution 2

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.

Share:
13,791

Related videos on Youtube

Tonyc
Author by

Tonyc

I'm a product manager and C# software developer usually on back-end solutions.

Updated on July 31, 2022

Comments

  • Tonyc
    Tonyc almost 2 years

    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?

  • Tonyc
    Tonyc over 4 years
    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
    Tonyc over 4 years
    For example with the configuration (code, appsettings.json, NLog.config): loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.‌​LogLevel.Information‌​); "Logging": { "LogLevel": {"Default": "Warning" }} <logger name="*" minlevel="Trace" writeTo="f" /> 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.
  • Rolf Kristensen
    Rolf Kristensen over 4 years
    @Tonyc Think you have to create an issue at github: github.com/NLog/NLog.Extensions.Logging/issues/new and attach solution as zip-file.
  • Rolf Kristensen
    Rolf Kristensen over 4 years
    Have replied to your issue: github.com/NLog/NLog.Extensions.Logging/issues/389 (Question and answer is not really related to NLog, but about MEL)
  • Rolf Kristensen
    Rolf Kristensen over 4 years
    Based on the code-sample that you posted here: github.com/NLog/NLog.Extensions.Logging/issues/389
  • Tonyc
    Tonyc over 4 years
    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
  • Ankush Jain
    Ankush Jain about 4 years
    This is what I was looking for.
  • Neo
    Neo over 3 years
    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.
  • Rolf Kristensen
    Rolf Kristensen over 3 years
    @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.