This is an old revision of the document!


Debugging
Using System.Diagnostics

Configuration File

Add the following to the app.exe.config file (must reside in the same folder and the app.exe):

<configuration>
...
<system.diagnostics>
    <sources>
      <source name="srcMyAppDebug" switchName="SourceSwitch" >
        <listeners>
          <add name="myTextListener" />
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="SourceSwitch" value="All" />
    </switches>
    <sharedListeners>
      <add name="myTextListener"
           type="System.Diagnostics.TextWriterTraceListener"
           initializeData="Debug.txt" />
    </sharedListeners>
    <trace autoflush="true" indentsize="4"></trace>
</system.diagnostics>
 
</configuration>

The SourceLevels used by the SourceSwitch (app.exe.config configuration file) could be any of these:

public enum SourceLevels
{
    All             = -1,
    Off             = 0,
    Critical        = 1,
    Error           = 3,
    Warning         = 7,
    Information     = 15,
    Verbose         = 31,
    ActivityTracing = 65280,
}

The listener could also be:

  <listeners>
     <add name="myXmlListener"
          type="System.Diagnostics.XmlWriterTraceListener"
          initializeData= "Debug.xml" />
  </listeners>

Writing Events

To write to the event log:

System.Diagnostics.Trace.TraceInformation("Some operation here: Hello World");
System.Diagnostics.Trace.TraceError("Error: Something failed here.");

Alternatively, and more flexible:

TraceSource srcMyApp = new TraceSource("srcMyApp");
srcMyApp.TraceInformation("Some operation here: Hello World");
srcMyApp.TraceEvent(TraceEventType.Error, 0, "Error: Something failed here.");

The TraceEventType could be any of these:

public enum TraceEventType
{
    Critical    = 1,
    Error       = 2,
    Warning     = 4,
    Information = 8,
    Verbose     = 16,
    Start       = 256,
    Stop        = 512,
    Suspend     = 1024,
    Resume      = 2048,
    Transfer    = 4096,
}

Another example:

using System.Diagnostics;
 
private void WriteToEventLog(string message)
{
  string cs = "srcMyApp";
  EventLog elog = new EventLog();
 
  if (!EventLog.SourceExists(cs))
  {
     EventLog.CreateEventSource(cs, cs);
  }
 
  elog.Source = cs;
  elog.EnableRaisingEvents = true;
  elog.WriteEntry(message);
}