Tracing in ASP.NET 2.0


Essential ASP.NET explained the basics of tracing in ASP.NET. Here we'll show the new features that have been added in version 2.0.

In the original tracing implementation, the requestLimit attribute on the <trace> element limited the number of requests that would generate tracing data. By default this value is set to 10, which means that only the first 10 requests will be traced; requests after that will be ignored by the tracing system. In version 2.0, you can set the new mostRecent attribute to true to indicate you'd like to continue tracing indefinitely, using requestLimit to control the number of requests that you want to see in the output. With this setting in place, you'll now see the 10 most recent requests traced at all times, instead of the 10 first trace messages (which seems a lot more useful!).

Programmatic Access to Trace Output

In the past, there wasn't a clean way to hook into the tracing infrastructure to control formatting or perhaps even redirect the trace output to another logging system. Version 2.0 adds a tracing event to which you can wire up code to intercept ASP.NET trace messages as they are generated. You can use this to format the trace output however you like, or to redirect the trace output to a persistent medium (although you might find the next section on System.Diagnostics integration more useful if this is your goal).

The TraceContext object, which is exposed via HttpContext.Trace and Page.Trace, now exposes an event called TraceFinished, which fires once all trace messages for a request have been gathered. When this event fires, the associated TraceContextEventArgs includes a property called TraceRecords that you can enumerate to programmatically walk through each TraceContextRecord for the current request. The example in Listing 7-15 writes trace data to a text file.

Listing 7-15. Writing trace output to a file

<!-- web.config to turn on tracing and supply trace filename --> <configuration>   <appSettings>     <add key="traceFile" value="c:\temp\trace_log.txt"/>   </appSettings>   <system.web>     <compilation debug="true"/>     <trace enabled="true" pageOutput="false" localOnly="true" />   </system.web> </configuration> // codebehind for a generic Tracing.aspx file that // wires up to TraceFinished and writes a text file using System; using System.IO; using System.Web; using System.Configuration; public partial class Tracing : System.Web.UI.Page {     protected void Page_Load(object sender, EventArgs e)     {         Trace.TraceFinished += Trace_Finished;         Trace.Write("Using Page Trace",                     "Subscribed to TraceFinished event");     }     void Trace_Finished(Object sender, TraceContextEventArgs e)     {         string traceFile =                ConfigurationManager.AppSettings["traceFile"];         using (StreamWriter w = File.AppendText(traceFile))         {             int i = 0;             foreach (TraceContextRecord r in e.TraceRecords)                 w.WriteLine("{0}) {1}:{2}", ++i,                             r.Category, r.Message);         }     } } 

While the example in Listing 7-15 will only record trace data for this one page, you could easily move this code into global.asax or an HttpModule where you'd watch for an event such as PreRequestHandlerExecute and use that to wire a handler onto HttpContext.Current.TraceContext.TraceFinished, enabling you to record traces for all pages in an application.

Integration with System.Diagnostics Tracing

ASP.NET 2.0 introduces a couple of adapters that make it easy to funnel trace messages back and forth between ASP.NET tracing and System.Diagnostics tracing. This is really helpful if you have existing components that use the Trace object in System.Diagnostics, or if you'd like to use the System.Diagnostics trace listeners to collect all trace data for your Web application.

To instruct ASP.NET to send trace output directly to the System.Diagnostics trace listeners you've configured in the <system.diagnostics> section of your web.config file, set the new writeToDiagnosticsTrace attribute of the <trace> element to true, as shown in Listing 7-16.

Listing 7-16. Sending trace output to System.Diagnostics trace listeners

<!-- web.config --> <configuration>   <system.web>     <trace enabled="true"            pageOutput="false"            writeToDiagnosticsTrace="true"/>     </system.web>   <system.diagnostics>     <trace>       <listeners>         <add name="console"              type="System.Diagnostics.ConsoleTraceListener"/>       </listeners>     </trace>   </system.diagnostics> </configuration> 

With this configuration, if you run a Web page in the debugger, you'll be able to see the trace records for any Web page in the debugger's output window. With this feature it's even easier to dump ASP.NET trace information to a persistent medium by simply wiring up one of the built-in trace listeners from System.Diagnostics.

If you want to go the other way, the ASP.NET team has also included a new trace listener that writes its output to the ASP.NET TraceContext. It's called, appropriately enough, System.Web.WebPageTraceListener, and if you wire it up under the <system.diagnostics> section of your web.config file, it'll funnel all System.Diagnostics trace messages back into the ASP.NET tracing system. This can be helpful if you're accustomed to using ASP.NET tracing and would like to include System.Diagnostics trace messages from non-ASP.NET components in your output.

The example in Listing 7-17 calls into a Calculator class which is instrumented with System.Diagnostics.Trace calls.

Listing 7-17. Funneling System.Diagnostics trace records into the ASP.NET tracing system

[View full width]

<!-- web.config that uses the WebPageTraceListener --> <configuration>   <system.web>     <trace enabled="true" pageOutput="false" localOnly="true" />   </system.web>   <system.diagnostics>     <trace>       <listeners>         <add name="aspnet" type="System.Web.WebPageTraceListener, System.Web, Version=2.0. 0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />       </listeners>     </trace>   </system.diagnostics> </configuration> // Tracing.aspx.cs // here's the codebehind that calls the Calculator using System; public partial class Tracing : System.Web.UI.Page {     protected double AddNumbers()     {         Trace.Write("Calling Calculator.Add");         return Calculator.Add(2, 2);     } } // here's the calculator code using System; using System.Diagnostics; public static class Calculator {     public static double Add(double a, double b)     {         double result = a + b;         Trace.TraceInformation("Calculator.Add({0} + {1}) = {2}",                                a, b, result);         return result;     } } 

Figure 7-5 shows the resulting output from trace.axd. Note how the Calculator's calls to Trace are included in line with the ASP.NET tracing data. This integration is sure to come in handy for a lot of people!

Figure 7-5. Funneling System.Diagnostics trace records into ASP.NET tracing


Funneling Web Events to System.Diagnostics Trace Listeners

ASP.NET 2.0 comes with a third adapter that lets you funnel Web events to the System.Diagnostics trace listeners. Simply wire up the TraceWebEventProvider as a normal Web event provider in the <providers> section of web.config to enable this feature. This provider doesn't require any configuration; it just forwards all Web events to the System.Diagnostics.Trace class. This is by far the simplest built-in Web event provider. Listing 7-18 shows the entire implementation of its ProcessEvent method.

Listing 7-18. TraceWebEventProvider.ProcesEvent

public override void ProcessEvent(WebBaseEvent eventRaised) {      if (eventRaised is WebBaseErrorEvent)      {            Trace.TraceError(eventRaised.ToString());      }      else      {            Trace.TraceInformation(eventRaised.ToString());      } } 

Note how this code checks to see if the incoming Web event derives from WebBaseErrorEvent to determine whether the event represents an error or not. This should help emphasize that when you create your own custom Web events, you should think carefully about the base class from which you derive. Don't just derive from WebBaseEvent blindlypick the most appropriate base class for each of your custom event classes.




Essential ASP. NET 2.0
Essential ASP.NET 2.0
ISBN: 0321237706
EAN: 2147483647
Year: 2006
Pages: 104

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net