在 asp.net 核心应用的调试 window 中显示 NLog 输出

Show NLog output in debug window of asp.net core app

是否可以在 Visual Studio 2017 调试 window 中显示 NLog(或内置调试器)正在记录的内容?

我将 NLog 设置为输出到一个文件,但对于开发来说,能够在调试 window 中看到调试消息真的很方便。我可以看到有关如何使用控制台执行此操作的文章,但对于 asp.net 项目,没有任何控制台输出,只有调试 window.

是的,对于 Asp.Net Core,有内置的记录器提供程序,如 ConsoleDebug 可以将日志写入 Output Window

如果您使用 WebHost.CreateDefaultBuilder(args),它将使用内置提供程序 ConsoleDebug,您可以通过 Output window 检查输出]-> Asp.NET Core Web Server 以获得干净的结果。

对于 NLog 中的 Getting started with ASP.NET Core 2,它使用以下代码清除所有其他日志提供程序。

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .ConfigureLogging(logging =>
    {
        logging.ClearProviders();
        logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
    })
    .UseNLog()  // NLog: setup NLog for Dependency injection
    .Build();

如果你还需要登录调试window,你可以修改如下代码:

        public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging(logger => {
                logger.AddNLog();
                //logger.AddConsole(); //UnComment out this line if you did not use CreateDefaultBuilder
            })
            .Build();

简单的解决方案就是使用 OutputDebugString-target(NetCore 支持)

https://github.com/NLog/NLog/wiki/OutputDebugString-target

示例:

<targets>
  <target name="debugger" xsi:type="OutputDebugString" layout="${logger}::${message}"/>
</targets>

<rules>
  <logger name="*" minlevel="Trace" writeTo="debugger" />
</rules>

另一种可以使用 xsi:type="debugger":

https://github.com/NLog/NLog/wiki/Debugger-target