首页 > 解决方案 > NLog 不记录调试消息

问题描述

我在 .NET Core 3.1 Worker Service 项目中记录调试级别消息时遇到问题。我的文件目标或控制台都没有记录调试级别的消息。信息级事件按预期写入。我已经查看了一个具有相同标题的旧问题,以确保选中所有这些框。

NLog.config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="%appdata%\FileTransferService\nlog-internal.log">

  <variable name="logdir" value="${specialfolder:folder=ApplicationData}/FileTransferService"/>
  <variable name="stdlayout" value="${longdate}|${level:uppercase=true}|${message:exceptionSeparator=|}${exception:format=ToString}"/>

  <targets>  
    <target name="default" xsi:type="AsyncWrapper" overflowAction="Block">
      <target name="defaultlog" xsi:type="File"
              fileName="${logdir}/dftslog.txt"
              layout="${stdlayout}"
              archiveEvery="Month" concurrentWrites="false"/>
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="default"/>
  </rules>
</nlog>

应用设置.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

我尝试将 Microsoft 和 Microsoft.Hosting.Lifetime 都设置为 Debug,但这没有任何效果。

Program.CreateHostBuilder 方法

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseWindowsService()
        .ConfigureLogging((context, logBuilder) => {
            logBuilder.ClearProviders();
            logBuilder.AddConfiguration(context.Configuration.GetSection("Logging"));
            logBuilder.SetMinimumLevel(LogLevel.Debug);
            logBuilder.AddConsole();
            logBuilder.AddNLog();
        })
        .ConfigureServices((hostContext, services) => {
            services.AddHostedService<Worker>();
            services.AddTransient(typeof(ITransferService), typeof(TransferService));
        });

以下是一些附加说明:

标签: c#logging.net-corenlog

解决方案


将 NLog 与 Microsoft-Extension-Logging (MEL) 一起使用时,NLog 将成为 MEL-LoggerFactory 中的 LoggingProvider。

这意味着在 MEL-LoggerFactory 中配置的任何过滤总是胜出,独立于 NLog.config。

MEL-LoggerFactory 将自动从appsettings.json(以及任何特定于环境的appsettings.development.jsonappsettings.production.json)加载其过滤。

即使调用SetMinimumLevel(LogLevel.Debug)了 ,那么其中的任何配置都appsettings.json将覆盖它。

另请参阅:https ://github.com/NLog/NLog.Web/wiki/Missing-trace%5Cdebug-logs-in-ASP.NET-Core-3%3F


推荐阅读