Last thursday and friday I gave a course on ASP.NET 2.0 services at KPN in Groningen. I was covering the tracing capabilities of ASP.NET (available since 1.0, BTW) and showing some of the new enhancements in 2.0. To my surprise I found that combining the tracing of ASP.NET and that of the System.Diagnostics namespace did not behave as I suspected.
There are two tracing systems in the .NET Base class libraries (BCL). The System.Diagnostics namespace has a very extensive set of types that allow advanced tracing if you need it. ASP.NET on the other hand has an in-page dump of information available, that also includes some simple trace information. The two classes that compete for your attention are System.Diagnostics.Trace and System.Web.TraceContext. I assume that you are familiar to some degree with both.
Anyway, ASP.NET 2.0 introduces a redirection of trace output from one tracing system to the other and vice versa. If you want your diagnostics trace (short for the System.Diagnostics.Trace subsystem) to end up inside your webpage (or be viewed from the http://myserver/mywebsite/trace.axd handler) you register the new WebPageTraceListener trace listener in your config.
Any calls to Trace.WriteLine during the page lifecycle and the like will also be viewable from that page’s trace dump.
Going the other way sending ASP.NET tracing information to diagnostics trace you can simply configure so in your web.config:
When configured like above, any calls to System.Web.TraceContext.Write or Warn will end up being send to the diagnostics trace. If the DefaultTraceListener is registered (it is by default, LOL), you can pick up all output of diagnostics trace during debugging in the output window of Visual Studio 2005. Or, you can use DebugView by SysInternals (free tools, go get the entire suite, now!) and see the trace info fly by.
Except, … when I tried to do so in my ASP.NET 2.0 web site (like above), nothing happened. Nothing in the output window during debugging, nor in DebugView, and nothing in the web page with the WebPageTraceListener. :O
Stomped at first I suddenly remembered the conditions for System.Diagnostics.Trace and Debug to work: the compiled assembly must have been compiled with the conditional compilation constants TRACE and DEBUG respectively. Otherwise the calls to Write and WriteLine aren’t actually made.
To test my theory I put the Trace.WriteLine code in a Class Library project and changed it ever so slightly:
When I called TraceLibrary.TraceDemo everything worked. So, what did that mean? By default the C# compiler is not configured to compile with the TRACE constant for ASP.NET 2.0 web sites.
The question then quickly becomes: How do I set the TRACE compilation constant? Here’s how.
Add a <system.codedom> section to your web.config containing the following:
That should get your diagnostics trace going and also put the output in ASP.NET trace if the webpage listener is set.