Saturday, September 18, 2010

Making custom trace listeners more configurable.

The .NET System.Diagnostics namespace provide some classes that can be used to trace the execution of your programm. There are some default listeners in the Diagnostics namespace which can be used to write the trace messages to a file, the event log, etc. You can also write your own trace listeners by extending/overwriting the TraceListener class. These trace listeners can be registered at runtime:
Trace.Listeners.Add(new ConsoleTraceListener());
Or you can specify listeners you want to use in the system.diagnostics section of your .config file:
<listeners>
  <add initializedata="MyEventLog"
        name="EventLogListener"    
        type="System.Diagnostics.EventLogTraceListener">
  </add>
</listeners>
If you use the .config file it would be nice to extend the xml tag by custom attributes. To do so you need to override the GetSupportedAttributes() method in your TraceListener-implementation. In this method you just need to return the names of the custom attributes you want to use in the .config file. For example if you have a custom trace listener that separates trace entries by a delimiter:
protected override string[] GetSupportedAttributes() {
  return new string[] { "delimiter" };
}
Now you can specify the delimiter in you .config file:
<listeners>
  <add delimiter=":"
    initializedata="delimitedOutput.txt" 
    name="delimitedListener"
    type="MyNamespace.MyDelimitedTraceListener">
  </add>
</listeners>
To get the value of the custom attribute you can use the Attributes property of the base class in your TraceListener implementation:
foreach (DictionaryEntry de in this.Attributes) {
  if (de.Key.ToString().ToLower() == "delimiter") {
    source = de.Value.ToString();
  }
}

Sunday, August 29, 2010

Reloaded

After a long time I decided to revive my blog. So here are some news and other stuff I found interesting during the last week: