Manage logging configuration with NLog in .NET Core 3

旧街凉风 提交于 2020-05-14 09:39:07

问题


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?


回答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




回答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.




回答3:


Refer this URL.you will get complete idea about Nlog in asp net core

https://www.c-sharpcorner.com/article/introduction-to-nlog-with-asp-net-core2/



来源:https://stackoverflow.com/questions/59648290/manage-logging-configuration-with-nlog-in-net-core-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!