Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manage logging configuration with NLog in .NET Core 3

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?

like image 935
Tonyc Avatar asked Jan 08 '20 14:01

Tonyc


People also ask

How to create a nlog file in NET Core?

NLog – File logging in Console application .NET Core 1 Getting Started 2 Create a .NET Core Console application. Here I have used the .NET Core 3.1 or .NET 5 Console application but the below technique will work any lower version of .NET ... 3 Using Generic HostBuilder for DI and logging. ... 4 Define NLog Configuration file. ... 5 Summary. ...

How to configure nlog logging in Visual Studio 2019?

NLog is an open-source logging framework that helps to easily configure logging for your .Net applications. It is also flexible to use with any .Net applications including .Net core and standard .Net applications. Let's create a simple .Net core web application and configure NLog logging. Open Visual Studio 2019 and Select " Create a New Project ".

How do I change the nlog output directory location?

So we need to change the property settings for this file, right-click on NLog.config and click properties and change the value for ‘ Copy to output directory" to ‘ Copy Always ’ or ‘Copy if newer ’ (please refer this article for more info : Logging in ASP.NET Core Application with NLog (Local file) ).

What is nlog?

What is NLog? NLog is a reliable and robust logging library for .NET. NLog makes the developer’s life easy by supporting various write targets like database, file, console, email, and so on.


1 Answers

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.

like image 151
Rolf Kristensen Avatar answered Oct 16 '22 15:10

Rolf Kristensen