- Posted by Ian Suttle on February 28, 2008
- Filed under .Net Framework | ASP.Net
You know the story... guy writes code... guy wants to debug code... guy wants to trace messages to understand what's happenin'... guy uses Trace.Write(). Now the part that smacked me in the tush with a wet towel this late night was the different between ASP.NET Trace.Write() and System.Diagnostics.Trace.Write(). In a default setup of an ASP.NET web app System.Diagnostics.Trace.Write() doesn't output to the Page Trace or the Trace.axd. It goes to the "standard output" whatever that might be (assumed to be a console window). This becomes problematic when you want to trace from a business object, data layer, server control, etc as these items have no HTTP Context which implements Trace as a System.Web.TraceContext property.
Alas my faithful reader you can add a trace listener to your web.config or programmatically to have all Trace.Write() methods output to the ASP.NET trace. There are a variety of trace listeners one can add including the WebPageTraceListener which is what satisfies our case here. Here's how you CaN GeTZ TrACe (my best LOLCats impression).
Trace Listener via config
<system.diagnostics>
<trace>
<listeners>
<add name="WebPageTraceListener"
type="System.Web.WebPageTraceListener, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</listeners>
</trace>
</system.diagnostics>
Trace Listener programmatically from the Global.asax
void Application_Start(Object sender, EventArgs e)
{
WebPageTraceListener gbTraceListener = new WebPageTraceListener();
System.Diagnostics.Trace.Listeners.Add(gbTraceListener);
}
Keep reading!
For your System.Diagnostics.Trace statements to write to the trace your project MUST be compiled with the TRACE compiler switch. In your project properties the Build tab has this defined as "Define TRACE constant".
Now for the reverse... you want to route all ASP.NET trace to the standard system tracing output. Modify your config to include an appropriate trace listener such as TextWriterTraceListener (note: WebPageTraceListener probably isn't appropriate for this one:) and update your web.config to have the trace element's writeToDiagnostics set to "true".
<system.web>
<trace writeToDiagnosticsTrace="true"/>
</system.web>