Friday, August 8, 2014

Setup TraceSource logging in a console application

Quick setup for getting tracing an XML file that can be loaded in Microsoft Service Trace Viewer

Create a console application in Visual Studio

Create a TraceSource in your application

namespace TraceDemoApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var traceSource = new TraceSource("TraceDemoApp");

            // TODO: write to the above TraceSource

            Console.ReadLine();
        }
    }
}

Write to said TraceSource

namespace TraceDemoApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var traceSource = new TraceSource("TraceDemoApp");

            traceSource.TraceEvent(TraceEventType.Verbose, 0, "This is a verbose message");
            traceSource.TraceEvent(TraceEventType.Information, 0, "This is an informational message");
            traceSource.TraceEvent(TraceEventType.Warning, 0, "This is a warning message");
            traceSource.TraceEvent(TraceEventType.Error, 0, "This is an error message");
            traceSource.TraceEvent(TraceEventType.Critical, 0, "This is a critical message");

            // Flush the trace source (if autoflush is not enabled) to ensure that data is written
            traceSource.Flush();

            Console.ReadLine();
        }
    }
}

Configure trace source in application configuration file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <system.diagnostics>
    <sources>
      <!-- Turn on all traces for the TraceDemoApp trace source -->
      <source name="TraceDemoApp" switchValue="All">
        <listeners>
          <add name="console"/>
          <add name="xmlListener"/>
          <!-- Optionally remove the default trace listener -->
          <!--<remove name="Default"/>-->
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <!-- Log traces to XML file that can be opened with Microsoft Service Trace Viewer -->
      <add name="xmlListener"
        type="System.Diagnostics.XmlWriterTraceListener"
        initializeData="C:\Logs\xmlWriterListenerLog.svclog"/>
      <!-- Log traces to console -->
      <add name="console"
           type="System.Diagnostics.ConsoleTraceListener"/>
    </sharedListeners>
  </system.diagnostics>
</configuration>

Run application and examine output in console and Microsoft Service Trace Viewer

Console Output
Microsoft Service Trace Viewer

Troubleshooting

No output

Verify that the trace source has a listener that is not the DefaultTraceListener
Only the DefaultTraceListener is listening to the trace source
The default trace listener uses Win32's OuputDebugString method, which will only log to an attached debugger or DebugView.