Controlling Tracing Output in Production Code

Controlling Tracing Output in Production Code


Mysterious bugs often appear at the client's site, even after the application is thoroughly tested. Most of the time these bugs are difficult, if not impossible, to reproduce on your development machine. Knowing this, you want an application with built-in instrumentation that's off by default but can easily be turned on when you need it.


Use the trace class for any tracing code that you might need to turn on after your application has been deployed. To turn on tracing at a client's site, provide the client with an application configuration file such as this one:

	<?xml version="1.0" encoding="utf-8" ?>
	            <add name="DatabaseSwitch" value="4"/>
	            <!-- 4 == TraceLevel.Verbose -->

	        <trace autoflush = "true" indentsize = "2">
	                <add name = "MyListener"
	                        type = "System.Diagnostics.TextWriterTraceListener"
	                        initializeData = " MyFileName.log"/>


Allowing tracing code to be enabled and used at a client site can be extremely useful when debugging problems in release code. This technique is even more useful when the problem cannot easily be reproduced in-house. For this reason, it isin some casesa wise practice to use the trace class instead of the Debug class when adding tracing code to your application.

To control the trace output at a client site, you can use an XML config file. This XML file must have the same base name as the executable that is to use these switches, followed by an extension of .exe.config. For example, if the executable name were Accounting.exe, the configuration file would be named Accounting.exe.config. This file should be placed in the same directory as the executable Accounting.exe.

The application configuration file always consists of the following two outer elements for diagnostic information:


(The configuration element may contain other child elements besides the system.diagnostics element.)

Within these elements, the switches and Trace elements may be added. These two elements contain information specific to switches and listeners. If your code contains a traceSwitch (as shown in the next example) or BooleanSwitch objector any other type derived from the Switch classyou can control this object's trace-level setting through the <switches> element in the configuration file:

	private static TraceSwitch ts = new TraceSwitch("DatabaseSwitch",
	        "Only allow database transactions to be logged");

The listeners element shown in the Solution adds a new traceListener-derived object to the listeners collection. Learn more about TRaceListener in Recipe 8.2. Any trace or Debug statements will use this new listener.

The switches element of the Solution can contain the three elements defined here:


Clears any previously added switch. In the world of ASP.NET, where web.config files are nested, this can be useful to clear settings that are inherited from previous configuration files.

<add name="Switch_Name" value="Number"/>

Adds new switch initialization information to be used at runtime. The name attribute defines the name of the switch that is used in your code. The value attribute is set to a number that turns the switch either on or off, in the case of a BooleanSwitch class, or defines the switch level (e.g., the amount of output you wish to receive), in the case of a traceSwitch class. To turn on a BooleanSwitch, use a nonzero value (negative numbers work here, too); to turn it off, use zero.

<remove name="Switch_Name"/>

Removes switch initialization information at runtime. The name attribute defines the name of the switch that is used in your code.

Immediately after the switches tags in the Solution are the TRace tags, although the ordering of these tags is up to you. The TRace tags can contain the following two optional attributes:

autoflush = true|false

Indicates whether the listener automatically flushes its buffer after every write (true) or not (false)

indentsize = "4"

Specifies the number of indent characters to use when indenting the output

Within the trace tags are the listeners tags, which, in turn, can contain any of the following defined tags:


Clears any previously added listeners. This tag also removes the DefaultTraceListener from the listeners collection.

<add name= "Listener_Name" type="Listener_Fully_Scoped_Type_Name" initializeData="String_Passed_Into_CTOR"/>

Adds a new listener to any trace and Debug classes used in your application. The name attribute defines the name of the listener that is used in your code. The type attribute is set to the listener's class name. The optional initializeData attribute allows a string to be passed in to the constructor of this listener. If you are using a custom listener, you will need to include a constructor that accepts a string as the only argument to prevent an exception from being thrown.

<remove name = "MyListener"/>

Removes a listener at runtime. The name attribute defines the name of the listener to be removed. This could be useful if another configuration file, such as he machine.config file, has already added a listener or if any listeners were created through your application's code. If more than one listener is added, the output will be written out twiceonce for each listener.

Regardless of whether your code defines trACE and/or DEBUG, the code will attempt to access this file for switch initialization information if a class derived from Switch is instantiated. The Switch class is discussed in Recipe 8.3. If you wish to prevent this behavior, place any code that instantiates a switch class inside of a method decorated with the ConditionalAttribute attribute:

	public class Traceable
	    BooleanSwitch DBSwitch = null;
	    BooleanSwitch UISwitch = null;
	    BooleanSwitch exceptionSwitch = null;

	    public void EnableTracing( )

	        DBSwitch = new BooleanSwitch("DatabaseSwitch",
	                   "Switch for database tracing");
	        UISwitch = new BooleanSwitch("UISwitch",
	                   "Switch for user interface tracing");
	        exceptionSwitch = new BooleanSwitch("ExceptionSwitch",
	                          "Switch for tracing thrown exceptions");

The ConditionalAttribute attribute prevents your application from calling the EnableTracing method when trACE is undefined and thereby keeps the switches from being used.

In addition to the application configuration file (MyApp.exe.config), a machine.config file is also located in the directory <Common Language Runtime install path>\CONFIG\. The configuration tags and all of their containing elements may be placed in this file as well. However, doing so will enable these switches and listeners on a machinewide level. This can cause applications that define their own listeners to behave strangely, especially if the listeners are duplicated. Additionally, the application will look for configuration information in the application configuration file first and the machine.config file second.

The application configuration file and the machine configuration file are both case-sensitive. Be sure that your tag names and their attributes are in the correct case. However, the string assigned to the name attribute does not seem to be case-sensitive, while other strings assigned to attributes are.

See Also

See the "Trace and Debug Settings Schema" topic in the MSDN documentation.

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows