简体   繁体   English

NLog 不记录调试消息

[英]NLog not logging debug messages

I'm having a problem with logging Debug level messages in a .NET Core 3.1 Worker Service project.我在 .NET Core 3.1 Worker Service 项目中记录调试级别消息时遇到问题。 Neither my file target or console are getting Debug level messages logged.我的文件目标或控制台都没有记录调试级别的消息。 Information level events are written as expected.信息级事件按预期写入。 I have reviewed an older question with the same title to ensure all those boxes are checked.我已经查看了一个具有相同标题的旧问题,以确保选中所有这些框。

NLog.config NLog配置文件

<?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>

appsettings.json应用程序设置.json

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

I've tried setting both the Microsoft and Microsoft.Hosting.Lifetime also to Debug, but that had no effect.我试过将 Microsoft 和 Microsoft.Hosting.Lifetime 也设置为调试,但这没有效果。

Program.CreateHostBuilder method 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));
        });

Here are a few additional notes:这里有一些额外的注意事项:

  • I tried calling SetMinimumLevel with no effect.我尝试调用 SetMinimumLevel 但没有效果。
  • The NLog.config is set to Copy Always. NLog.config 设置为始终复制。
  • I get the same results without AddConsole.我在没有 AddConsole 的情况下得到相同的结果。 That was actually added after I saw that debug messages weren't getting logged.这实际上是在我看到没有记录调试消息后添加的。

When using NLog together with Microsoft-Extension-Logging (MEL), then NLog becomes a LoggingProvider in the MEL-LoggerFactory.当 NLog 与 Microsoft-Extension-Logging (MEL) 一起使用时,NLog 将成为 MEL-LoggerFactory 中的 LoggingProvider。

This means any filtering configured in MEL-LoggerFactory always wins, independent of NLog.config.这意味着在 MEL-LoggerFactory 中配置的任何过滤总是获胜,独立于 NLog.config。

MEL-LoggerFactory will automatically load its filtering from appsettings.json (along with any environment-specific appsettings.development.json or appsettings.production.json ). MEL-LoggerFactory 将自动从appsettings.json (以及任何特定appsettings.development.json环境的appsettings.development.jsonappsettings.production.json )加载其过滤。

Even if having called SetMinimumLevel(LogLevel.Debug) , then any configuration in appsettings.json will override this.即使调用了SetMinimumLevel(LogLevel.Debug)appsettings.json任何配置也会覆盖它。

See also: https://github.com/NLog/NLog.Web/wiki/Missing-trace%5Cdebug-logs-in-ASP.NET-Core-3%3F另见: https : //github.com/NLog/NLog.Web/wiki/Missing-trace%5Cdebug-logs-in-ASP.NET-Core-3%3F

The problem appears to be with Visual Studio 2019.问题似乎出在 Visual Studio 2019 上。

Although the problem itself persists, the debug level events are written to both the console and the flat file when I run the application outside of Visual Studio.尽管问题本身仍然存在,但当我在 Visual Studio 之外运行应用程序时,调试级别的事件会同时写入控制台和平面文件。 This is not due to the debugger as I might have expected, because it exhibits the same behavior if I run it without the debugger within Visual Studio.这不是由于我可能预期的调试器造成的,因为如果我在 Visual Studio 中没有调试器的情况下运行它,它会表现出相同的行为。

I looked through Visual Studio settings and did a quick search, but I couldn't find anything related.我查看了 Visual Studio 设置并进行了快速搜索,但找不到任何相关内容。 That said, knowing that the events will be logged outside of Visual Studio solves my problem to the extent necessary.也就是说,知道事件将在 Visual Studio 之外记录在必要的程度上解决了我的问题。

To add to the accepted answer (not enough points for a comment):要添加到已接受的答案(评论不足):

Same problem.同样的问题。 But it also works correctly from within VS2019 when I use但是当我使用时,它也可以在 VS2019 中正常工作

private static Logger _logger = LogManager.GetCurrentClassLogger();

which I prefer over DI to get my logger (mainly because I like writing .Warn(...) over .LogWarning(...)我更喜欢用 DI 来获取我的记录器(主要是因为我喜欢写 .Warn(...) 而不是 .LogWarning(...)

I still set up DI for NLog so external/ms libraries will use it我仍然为 NLog 设置 DI,因此外部/ms 库将使用它

Rolf has the correct answer.罗尔夫有正确的答案。 Here is a sample code that will allow you to add Trace level during DEBUG sessions.这是一个示例代码,允许您在 DEBUG 会话期间添加跟踪级别。

_services.AddLogging(loggingBuilder =>
{
    #if DEBUG
    // Add Trace/Debug statements to the output.
    loggingBuilder.Services.TryAddEnumerable(                    
        ServiceDescriptor.Singleton<IConfigureOptions<LoggerFilterOptions>>(
            new ConfigureOptions<LoggerFilterOptions>(
                options => options.MinLevel = LogLevel.Trace)));
    #endif
    loggingBuilder.AddNLog(NLog.LogManager.Configuration);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM