Logo 
Search:

.Net Framework FAQ

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

Can I redirect tracing to a file?

  Shared By: Corey Brown    Date: Nov 09    Category: .Net Framework    Views: 1482

Answer:

Yes. The Debug and Trace classes both have a Listeners property, which is a collection of sinks that receive the tracing that you send via Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection contains a single sink, which is an instance of the DefaultTraceListener class. This sends output to the Win32 OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method. This is useful when debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose.

Here's how to use the TextWriterTraceListener class to redirect Trace output to a file:

Trace.Listeners.Clear();
FileStream fs = new FileStream( @"c:\log.txt", FileMode.Create, FileAccess.Write );
Trace.Listeners.Add( new TextWriterTraceListener( fs ) );

Trace.WriteLine( @"This will be writen to c:\log.txt!" );
Trace.Flush();
Note the use of Trace.Listeners.Clear() to remove the default listener. If you don't do this, the output will go to the file and OutputDebugString(). Typically this is not what you want, because OutputDebugString() imposes a big performance hit.

Share: 
 

Didn't find what you were looking for? Find more on Can I redirect tracing to a file? Or get search suggestion and latest updates.


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


Tagged: