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

Syn*_*tax 2 c# nlog .net-core asp.net-core

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

日志注册:

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

我正在获取日志输出,但它与.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>
Run Code Online (Sandbox Code Playgroud)

示例日志输出:

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.
Run Code Online (Sandbox Code Playgroud)

Ily*_*kov 7

这里有几个问题.

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

loggerFactory.AddConsole();
loggerFactory.AddDebug();
Run Code Online (Sandbox Code Playgroud)

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

loggerFactory.AddNLog();
loggerFactory.ConfigureNLog("nlog.config");
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

  • 注意:调试器目标在netstandard中不可用,请参阅https://github.com/NLog/NLog/wiki/platform-support (3认同)