自动将System.diagnostics.trace消息记录到Nlog目标

问题描述 投票:10回答:3

假设您在整个应用程序中都有C#跟踪消息。就像是:

Trace.TraceInformation("Service Started"); 

如何自动将此日志记录到nLog目标,而无需向具有跟踪消息的所有类添加如下代码?

using NLog;
private static Logger logger = LogManager.GetCurrentClassLogger();

有没有办法在不包含.NET Framework本身生成的跟踪的情况下执行此操作,this article演示了如何操作?

c# trace nlog system.diagnostics
3个回答
9
投票

这适用于没有明确来源的情况

  <system.diagnostics>
      <trace autoflush="true" indentsize="4">
        <listeners>
          <add name="MyNLogTraceListener" type="NLog.NLogTraceListener, NLog" />
          <remove name="Default" />
        </listeners>
      </trace>
  </system.diagnostics>

6
投票

你可以使用NLog的NLogTraceListener

为了完整性,这里是System.Diagnostics配置(来自上面的链接)来指定NLogTraceListener:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <sources>
      <source name="System.Net" switchValue="All">
        <listeners>
          <add name="nlog" />
        </listeners>
      </source>
      <source name="System.Net.Sockets" switchValue="All">
        <listeners>
          <add name="nlog" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="nlog" type="NLog.NLogTraceListener, NLog" />
    </sharedListeners>
  </system.diagnostics>
</configuration>

您还需要配置NLog,告诉它在从System.Diagnostics.Trace移动到NLog后如何编写信息:

<nlog>
  <targets>
    <target name="console" type="ColoredConsole" layout="${longdate} ${windows-identity} ${message}" />
  </targets>

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

0
投票

您可以在App.config中使用以下内容

    <system.diagnostics>

    <sources>
      <source name="System" switchValue="All">
        <listeners>
          <add name="nlog" />
        </listeners>
      </source>
    </sources>

    <sharedListeners>
      <add name="nlog" type="NLog.NLogTraceListener, NLog" />
    </sharedListeners>

    <trace autoflush="true" indentsize="4">
      <listeners>
        <add name="nlog" />
        <remove name="Default" />
      </listeners>
    </trace>

  </system.diagnostics>
© www.soinside.com 2019 - 2024. All rights reserved.