ASP.NET Core NLog nlog.config 已加载但被忽略

ASP.NET Core NLog nlog.config loaded but ignored

我正在编写一个 asp.net 核心应用程序,使用 NLog.Logging.Extensions 来提供日志记录。

登录注册:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
    loggerFactory.AddNLog();
    loggerFactory.ConfigureNLog("nlog.config");
    loggerFactory.AddConsole();
    loggerFactory.AddDebug();
    app.UseMvc();
}

我正在获取日志输出,但是它与我在 .config 文件中定义的日志记录布局的格式不匹配,并且它没有显示以下任何信息(但同样,它被配置为显示跟踪和上面的配置文件中)。

是否有人能够阐明为什么会发生这种情况?

nlog.config:

<?xml version="1.0" encoding="utf-8"?>
<nlog>
    <variable name="Layout" value="${longdate} ${level:upperCase=true} ${message} (${callsite:includSourcePath=true})${newline}${exception:format=ToString}"/>
    <targets>
        <target name="debugger" type="Debugger" layout="${Layout}" />
        <target name="console" type="ColoredConsole" layout="${Layout}" detectConsoleAvailable="False"/>
    </targets>
    <rules>
        <logger name="*" minlevel="Trace" writeTo="debugger,console" />
    </rules>
</nlog>

示例日志输出:

Hosting environment: Development 
Content root path: /Users/###/dev/###/Services/src/app/###/### 
Now listening on: http://localhost:8888 Application started. 
Press Ctrl+C to shut down. 
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
          Request starting HTTP/1.1 GET http://localhost:8888/State
info: ###.###.###[0]
          Building ### instance.

这里有几个问题。

1. 您获得日志输出是因为您附加了默认的 .NET Core 记录器:

loggerFactory.AddConsole();
loggerFactory.AddDebug();

这就是输出与布局格式不匹配的原因。如果您打算仅使用 NLog,请不要添加默认记录器。然后,将这两行保留在下面:

loggerFactory.AddNLog();
loggerFactory.ConfigureNLog("nlog.config");

2. NLog 配置损坏。 <add assembly="NLog.Web.AspNetCore"/> 丢失。此外,看起来 Debugger 目标正在破坏 NLog 中的某些内容。

下面有一个完全可行的 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">

  <!-- Load the ASP.NET Core plugin -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <variable name="Layout"
            value="${longdate}|${level:uppercase=true}|${logger}|${message}"/>

  <targets>
    <target name="console" 
            type="ColoredConsole"
            layout="${Layout}"
            detectConsoleAvailable="False"/>
  </targets>

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

其他示例:https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-(project.json)