我有这个程序
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
这是预料之中的,因为据我了解,当我们编译程序时,会得到调试日志。但是当我使用dotnet run -c Release
在发行版中进行编译时,我仍然可以在控制台中获得它
dbug:debuglogtest.Worker [0] _logger.LogDebug
但是在DebugView中什么也没有:
我期望什么:
_logger.LogDebug
在调试时在控制台和DebugView中都编写,在Release中进行编译时没有地方Debug.WriteLine
是用DebugView编写的实际情况:
_logger.LogDebug
仅写入控制台,而不以调试模式写入DebugView Debug.WriteLine
仅在以调试模式编译时才能正确编写。
我以为LogDebug
是在幕后打电话给Debug.WriteLine
,但也许Debug.WriteLine
和Logger.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中,但不能同时处于调试和发布模式。