Logger.LogDebug与Debug.WriteLine

时间:2020-05-31 19:50:57

标签: c# logging .net-core

我有这个程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace debuglogtest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                });
    }
}

和这个工人

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace debuglogtest
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogDebug("_logger.LogDebug");
            _logger.LogTrace("_logger.LogTrace");
            Debug.WriteLine("Debug.WriteLine");
        }
    }
}

和此配置

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

在调试dotnet run -c Debug中运行此命令时,我会在控制台中获取该消息

dbug:debuglogtest.Worker [0] _logger.LogDebug

这在DebugView中 DebugView of debug output

这是预料之中的,因为据我了解,当我们编译程序时,会得到调试日志。但是当我使用dotnet run -c Release在发行版中进行编译时,我仍然可以在控制台中获得它

dbug:debuglogtest.Worker [0] _logger.LogDebug

但是在DebugView中什么也没有:

DebugView of release output

我期望什么:

  1. _logger.LogDebug在调试时在控制台和DebugView中都编写,在Release中进行编译时没有地方
  2. 在调试中编译时,
  3. Debug.WriteLine是用DebugView编写的

实际情况:

  1. _logger.LogDebug仅写入控制台,而不以调试模式写入DebugView

Debug.WriteLine仅在以调试模式编译时才能正确编写。

我以为LogDebug是在幕后打电话给Debug.WriteLine,但也许Debug.WriteLineLogger.LogDebug是两回事?我肯定看起来像。我认为这很令人困惑,因为我们需要在两个不同的地方(调试和过滤时)控制Debug日志记录。如果我阅读文档:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1#debug,它说它调用了相同的Debug.WriteLine

Debug提供程序使用System.Diagnostics.Debug类写入日志输出。调用System.Diagnostics.Debug.WriteLine写入Debug提供程序。

我做错什么了吗?我一定是误会了我希望能够在调试模式下进行编译时控制Logger.Debug。那不可能吗?

更新

如果我检查了源代码(即使它已经很旧了(有人知道更新的引用,请指定)):https://github.com/aspnet/Logging/blob/master/src/Microsoft.Extensions.Logging.Debug/DebugLogger.debug.cs我可以看到它定义了#define DEBUG,并调用了{ {1}},但它并没有加在我的脑海中。它应该显示在DebugView中,但不能同时处于调试和发布模式。

1 个答案:

答案 0 :(得分:1)

ILogger.LogDebugILogger.LogTrace等有关消息的LogLevel,而不是消息的写入位置,基本上等效于调用具有相应值{{ 1}}参数。日志消息的写入目的地由您使用的记录器决定(控制台,文件,ETW,我敢肯定,您甚至可以创建一个写入调试视图的记录器,请参见文档的Log(..))。 logLevel允许您过滤实际写入日志目标的日志级别,该日志级别由应用程序设置而不是由构建配置直接控制(尽管您可以为不同的配置设置不同的设置)。