首页 > 解决方案 > 在 .NET Core 3 中使用 NLog 管理日志记录配置

问题描述

我在 .NET Core 3.1 辅助服务应用程序中使用 NLog。按照 NLog 的教程,我插入了一个 nlog.config 文件来管理配置。

现在我很困惑,因为我有三点配置日志记录:

  1. 在我需要在依赖注入上下文中创建记录器的代码中

    // 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. 在 appSettings.json

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

    nuget包安装产生的默认配置文件:

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

我看到的是,如果我删除 Nlog.config 文件,将不会创建日志文件。其他更改接缝没有效果。

这些配置有什么关系?打开/关闭日志记录和设置级别的最佳方法是什么?

标签: .net-corenlogilogger

解决方案


决定使用 NLog 的人通常还希望禁用所有 MEL 过滤以避免与两个过滤系统混淆。所以NLog wiki-tutorial是针对这些用户的。

我猜首先是 MEL 用户的人可能只会使用new HostBuilder().CreateDefaultBuilder().Build()(将在启用所有枪支的情况下设置所有内容)。

但是,如果继续使用简单示例,则需要删除:

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

并添加:

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

所以它看起来像这样:

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

ILoggingBuilder.AddConfiguration可以在 Nuget 中找到:Microsoft.Extensions.Logging.Configuration


推荐阅读