Home »

Can I customise the trace output?

Question ListCategory: ASP.NETCan I customise the trace output?
jully882 author asked 8 years ago
1 Answers
ethanbrown author answered 8 years ago

Yes. You can write your own TraceListener-derived class, and direct all outputthrough it. Here’s a simple example, which derives from
TextWriterTraceListener (and therefore has in-built support for writing to
files, as shown above) and adds timing information and the thread ID for
each trace line:
class MyListener : TextWriterTraceListener
{
public MyListener( Stream s ) : base(s)
{
}
public override void WriteLine( string s )
{
Writer.WriteLine( “{0:D8} [{1:D4}] {2}”,
Environment.TickCount – m_startTickCount,
AppDomain.GetCurrentThreadId(),
s );
}
protected int m_startTickCount = Environment.TickCount;
}
(Note that this implementation is not complete – the TraceListener.Write
method is not overridden for example.)
The beauty of this approach is that when an instance of MyListener is added
to the Trace.Listeners collection, all calls to Trace.WriteLine() go through
MyListener, including calls made by referenced assemblies that know nothing
about the MyListener class.

Please login or Register to Submit Answer