## Tuesday, 13 December 2011

### Overriding TextWriteTraceListener Part1 - Custom format your trace messages

If you want to customise the messages that are written to a text file, via the TextWriterTraceListener class, it is deceptively simple.

It took me a while to figure out how to do this because most people are either posting about writing a custom trace listener by inheriting from TraceListener class (but this has mostly abstract methods that you need to implement from scratch).

I just wanted to change the format of the messages being written to the trace, eg to put a DateTime value at the start of each line.

1. Create a new class which inherits from TextWriterTraceListener
2. Over-ride the WriteLine method, providing your customised formatting and making sure to utilise the existing functionality in the base class
> NOTE: Make sure you are over-riding the WriteLine() method (not Write or any of the other similar methods) which takes just a string message parameter, otherwise you will probably find that the application will compile and run fine but no traces will be written to your file!
3. Provide a constructor which takes a path.
> NOTE: Make sure that this constructor calls the base constructor otherwise you will probably find that the application will compile and run fine but no traces will be written to your file!
4. Add your new derived listener class to the collection of Listeners and tell it which file to output the messages to - this can be done programmatically, say in Application_Startup event or in a .config file - which is my preference as this allows you to change the location of the output file without re-compiling.
> NOTE: Make sure that you provide the name of assembly (in which your derived listener resides) to the the 'type' attribute listener entry you are adding to the listeners collection
eg type="MyApp.Global.MyNewTraceListener, AssemblyName"
The code for the derived listener class:

public class ASMSTraceListener : TextWriterTraceListener
{
//public ASMSTraceListener() : base() { }

public ASMSTraceListener(string path) : base(path)
{

}

public override void WriteLine(string message)
{
base.Write(DateTime.Now.ToString() + " ");
base.WriteLine(message);
}
}

The section for your .config file:

<system.diagnostics>
<trace autoflush="true">
<listeners>
</system.diagnostics>