C# Source Code: Creating a Trace Listener to send debug messages to a TextWriter
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Creating a Trace Listener to send debug messages to a TextWriter
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Tuesday, April 06, 2004
Hits:
2811
Category:
Attributes/Reflection/Debugging
Article:
C# provides easy access to the trace output messages that are generated by the Trace and Debug classes (in the System.Diagnostics) namespace. This output is sent to TraceListener objects which are responsible for handling these messages. By default the messages will be sent to the DefaultTraceListener which will send messages to Visual Studio applications via the debug window. The following code uses a BooleanSwitch class along with the application config file to conditionally stream debug messages to a text file in the application directory. using System; using System.Diagnostics; using System.IO; namespace vbUsers.Debugging /*Save the following XML switch (value=1 is enabled, value = 0 is disabled) in the application config file (ie. in the application directory (eg. [apppath]\bin\Debug) called myApp.exe.config.
*/ { /// Demonstration Code class DebuggingTest { [STAThread] static void Main(string[] args) { // Create a Boolean Switch using the XML in the app.config file BooleanSwitch mySwitch = new BooleanSwitch("mySwitch","Application Tracing"); // Create file stream FileStream stream = new FileStream(@"C:\Debug.txt",FileMode.Create); // Create listener using filestream TextWriterTraceListener listener = new TextWriterTraceListener(stream,"FileListener"); // Add listener to collection Trace.Listeners.Add(listener); // Add application code here Debug.WriteLine("Test Message, will always be writen","General"); // Condition debug message, will only be sent if the switch is enabled Debug.WriteLineIf(mySwitch.Enabled,"Test Message, will only be writen if the switch is enabled","Conditional"); // Flush and close the listener (also closes filestream) listener.Flush(); listener.Close(); // Remove listener from collection (stops the messages being sent to file) Trace.Listeners.Remove("FileListener"); } } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet