Automatically log System.diagnostics.trace message

2019-02-16 15:30发布

问题:

Say you have C# trace messages all over an application. Something like:

Trace.TraceInformation("Service Started"); 

How do you automatically log this to an nLog target without having to add code like the following to all the classes that have trace messages?

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

Is there a way to do this without including traces produced by the .NET Framework itself, which this article demonstrates how to do?

回答1:

This works for cases where there isn't an explicit source

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


回答2:

You can use NLog's NLogTraceListener.

For completeness, here is the System.Diagnostics configuration (from the link above) to specify the 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>

You also need to configure NLog to tell it how to write the information once it moves from the System.Diagnostics.Trace to NLog:

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

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