Thursday, April 3, 2008

How to redirect Trace output.

As we know, for tracing we can use method Trace.WriteLine(). But usually, we want to avoid a creating of detailed log file in production mode and to enable the tracing for testing and debugging purposes only by a configuration changing. So, we should find a way to redirect output of Trace.WriteLine() from standard output to a log file and configures the redirection without rebuilding of application.

Let's write next c# code:

Trace.WriteLine("messageTrace");
Trace.WriteLine("messageError", "Error");
Trace.TraceError("traceErrorMessage");

and define .config file:

redirectTrace_va_ConfigFile

Thus, we delete "Default" Trace Listener and add our "myListener' of type TextWriterTraceListener with parameter (log file name) c:\myListener.log.

Additionally, attribute "autoflush" is set in True and method Trace.WriteLine() will store input messages to log file immediately.

Content of file myListener.log:

myListenerLogFileContent

Reference:

How to configure Trace listener

No comments: