Automatically log System.diagnostics.trace messages to an Nlog target

Solracnapod picture Solracnapod · Nov 6, 2012 · Viewed 9.2k times · Source

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?

Answer

fiat picture fiat · Aug 12, 2013

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>