Pages

Advertisement

Wednesday, July 11, 2007

ASP.NET Tip: Adding Tracing to an Application

For some applications, such as console or Windows Forms applications, it's fairly easy to step through them to debug an issue. However, tracing down errors in web applications and services can be difficult, especially if they happen only in production environments where debugging isn't possible. In these cases, it's helpful to be able to add trace statements to your code that appear only when tracing is enabled on the web page or the web site

Step 1 is to enable tracing, either at a page or site level. To enable tracing for a single page, add the following to the @Page directive in your ASPX file:

Trace="true"

By default, this will dump the tracing information at the bottom of the web page. In most debugging/tracing situations, this is sufficient. However, if you're working on tracing in an entire site, you can make the change in the Web.config file instead of in each web page. To do this, open up the Web.config and add the following line:

<trace enabled="true" localOnly="false" pageOutput="true" />

The enabled attribute turns tracing on and off. The localOnly attribute controls whether the trace output shows up on machines other than the web server. In my own development environment, I use VMWare Workstation to host a Windows 2003 Server instance. So, I have to turn this attribute to false to see the output when I bring up a browser outside the virtual machine. If you are running IIS locally on your development machine, you won't need to set this attribute. The final attribute indicates that the output should be dumped at the bottom of the page. You also can opt to put the tracing in a separate file, but I've found that having the information right on the page is far easier to work with.

If you add this to a normal web page, you'll get all of this information:


Having all this information can make it much easier to debug issues, even before you add your custom messages.

To add custom messages to the trace output, you can use the Trace object property of the Page class to send messages into the list of events that is dumped to the web page. Here's an example:

Trace.Write("Current value of variable: " & variableValue.ToString());

This will print the line of text at the appropriate time during all the other events that are documented in the trace output. Because tracing can be turned on and off through a configuration file, this is an easy way to leave in debugging commands that you may need in the future. However, because it can be easily enabled and disabled, be careful about how much personal information, such as identification numbers and passwords, you dump into the trace output.

No comments:

Post a Comment