Musings

A random collection

.NET: Trace Logging to Console in C# Applications

In your code put the Trace messages at strategic places

  System.Diagnostics.Trace.TraceInformation(string message);

  System.Diagnostics.Debug.WriteLine("a debug message");

  // this is convenient
  System.Diagnostics.Debug.WriteLineIf(iUnitQty > 50, "This message WILL appear");

  // can event direct log messages to wherever
  TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
  Debug.Listeners.Add(tr1);
        
  TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));
  Debug.Listeners.Add(tr2);

  TextWriterTraceListener myCreator = new TextWriterTraceListener(System.Console.Out);
  Trace.Listeners.Add(myCreator);

Note: Debug messages will not appear in Release builds, they will be enabled only in Debug builds. Trace messages however will show up in Release & Debug builds.

Stick the following XML in your app.config in “<configuration>” section

  <system.diagnostics>
    <trace autoflush="true" indentsize="4">
      <listeners>
        <add name="configConsoleListener"
             type="System.Diagnostics.ConsoleTraceListener" />
      </listeners>
    </trace>
  </system.diagnostics>

Or

  <system.diagnostics>
    <trace autoflush="true" indentsize="4">
      <listeners>
        <add initializeData="...\console-host.svclog" type="System.Diagnostics.XmlWriterTraceListener" name="traceListener">
            <filter type=""/>
        </add>

        <add name="FileListener"
                 type="System.Diagnostics.TextWriterTraceListener"
                 initializeData=".\blabla-trace.txt" /> 
      </listeners>
    </trace>
  </system.diagnostics>

To add a timestamp or a datetime add TraceOutputOption to your config file:

        <add name="FileListener"
                 type="System.Diagnostics.TextWriterTraceListener"
                 initializeData=".\blabla-trace.txt"
                 traceOuputOptions="DateTime"       <!-- Timestamp|HostName|ThreadID|... -->
                 /> 
Advertisements

Written by curious

January 27, 2011 at 10:24 am

Posted in dotNET

%d bloggers like this: