Logo 
Search:

.Net Framework FAQ

Submit Interview FAQ
Home » Interview FAQ » .Net FrameworkRSS Feeds

Can I customise the trace output?

  Shared By: Fred Hicks    Date: Feb 06    Category: .Net Framework    Views: 664

Answer:

Yes. You can write your own TraceListener-derived class, and direct all output through 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.

Share: 
 

Didn't find what you were looking for? Find more on Can I customise the trace output? Or get search suggestion and latest updates.


Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: