ASP.NET Tracing

 

Error handling and tool-assisted debugging are essential instruments to make an application run without anomalies and recover gracefully from unexpected exceptions. Tools for tracing complete the kit. Tracing refers to the ability to output messages commenting on the execution of the code. This feature is extremely useful for tracking data inconsistencies, monitoring the flow, asserting conditions, and even gathering profiling information.

The .NET Framework comes with a rather feature-rich set of tools for tracing applications. In particular, the Systems.Diagnostics namespace defines two classes, named Trace and Debug, whose methods can be used to trace the code. The Trace and Debug classes are essentially identical and work on top of more specialized modules known as "listeners." The listener acts like a driver, collects tracing messages, and stores the messages in a particular medium such as the Windows event log, an application window, or a text file. Each application can have its own set of listeners, which will receive all emitted messages. The ASP.NET support for tracing is different and fairly disjointed, at least in ASP.NET 1.x.

ASP.NET comes with a made-to-measure subsystem to provide applications with diagnostic information about individual requests. The tracing subsystem is part of the infrastructure, and all that an application or a page has to do is enable it.

Tracing the Execution Flow in ASP.NET

Tracing lets developers write and leave debug statements in the code and turn them on and off through an attribute, and they can even do this once the application is deployed to a production server. When tracing for a page is enabled, ASP.NET appends diagnostic information to the page's output or sends it to a trace viewer application. For the most part, trace information has a fixed layout and fixed content, but page and control authors can customize it to some extent.

Enabling Page Tracing

Although a <trace> configuration section does exist in the web.config file to let you configure tracing at the application level, you typically want to control tracing on a per-page basis. However, for large projects you can toggle on and off the trace attribute by using the following code in the application's web.config file:

<configuration>     <system.web>         <trace enabled="true" pageOutput="true" />     </system.web> </configuration> 

The enabled attribute enables tracing on the application, while the pageOutput attribute permits output to appear in the page. If pageOutput is set to false (the default setting), the tracing output is automatically routed to the ASP.NET tracer tool trace.axd. At the end of the project, you simply drop the <trace> element from the web.config file or set both attributes to false. In this way, you eliminate at the root the risk of inadvertently leaving tracing enabled on one of the application pages.

The trace attribute in the @Page directive defaults to false; if set to true, it enables tracing information to appear at the bottom of pages, as shown in Figure 5-8.

image from book
Figure 5-8: ASP.NET tracing in action.

The trace information is part of the page and, as such, displays through any type of browser that accesses the page. Several tables of information show up along with the trace information generated by the page. Additional tables display request details, the control tree, and some useful collections such as cookies, headers, form values, and server variables. If the session and the application state are not empty, the contents of the Session and Application intrinsic properties are also included in the view.

The @Page directive also supplies the TraceMode attribute to let you choose the order in which the information should be displayed. Feasible values are SortByCategory and SortByTime. By default, the trace messages appear in the order in which they are emitted. If you set the TraceMode attribute to the SortByCategory value, the rows appearing in the Trace Information section are sorted by category name. The category to which each row belongs is determined by the method used to emit the message.

Enabling Tracing Programmatically

The Page class provides two properties to control tracing programmatically. They are TraceModeValue and TraceEnabled. As the names suggest, both are the programmatic counterpart of the aforementioned @Page directive attributes. TraceEnabled is a read/write Boolean property that turns tracing on and off for the specified page. TraceModeValue gets and sets a value in the TraceMode enumeration to indicate the desired tracing mode of the page either sort by category or by time.

To be honest, enabling and disabling output trace programmatically is not a feature that many applications require in a production scenario. The feature, though, might be valuable during the development cycle.

Writing Trace Messages

A third property on the Page class that is relevant to tracing is Trace an instance of the TraceContext class. An ASP.NET page populates its trace log using methods on the TraceContext class. An instance of this class is created when the HTTP request is set up for execution. The trace object is then exposed through the Trace property of the HttpContext class and is mirrored by the Trace property on the Page class.

The TraceContext Class

The TraceContext class has a simple interface and features a couple of properties and as many methods. The properties are IsEnabled and TraceMode. The IsEnabled property is a read-only Boolean property that indicates whether tracing is enabled. The value that this property returns is affected by the trace attribute on the @Page directive as well as the enabled attribute in the <trace> section of the web.config file. The TraceMode property gets and sets the order in which the traced rows will be displayed in the page. The property is of type TraceMode an enumeration that includes values such as SortByCategory and SortByTime.

Emitting Trace Messages

To emit messages, you can use either of two methods: Write or Warn. Both methods have three overloads, which all behave in the same way. Write and Warn are nearly identical methods the only visible difference is that Warn always outputs messages in red:

public void Write(string); public void Write(string, string); public void Write(string, string, Exception); 

The simplest overload just emits the specified text in the Message column. (See Figure 5-8.) In the second overload, the first string argument represents the name of the category you want to use for the message the second argument. The category name can be used to sort trace information and is any name that makes sense to the application to better qualify the message. Finally, the third overload adds an extra Exception object in case the message is tracing an error. In this case, the text in the Message column is the concatenation of the specified text and the exception's message.

Note 

Although the text being passed to both Write and Warn methods is meant to be displayed in HTML pages, no HTML formatting tag is ever processed. The text is written as plain text so that if you attempt to use boldface characters, your only result is having a trace message with <b> and </b> substrings.

Tracing from External Classes

The ASP.NET Trace object is accessible without a fully qualified name from the source code of the page or from the code file class. Custom controls embedded in the page, and their code file classes, can also access the tracing subsystem directly. Other classes don't have the same possibility, though.

Suppose your code-behind class delegates an external class to accomplish some tasks. How can the worker class trace in the ASP.NET page? In the context of the worker class, the Trace object is unavailable, or at least not in its unqualified form. External classes that want to emit text in the trace log of the current HTTP request can do that using the following expression:

System.Web.HttpContext.Current.Trace.Write(category, msg); 

In ASP.NET 2.0, you can configure the tracing subsystem to automatically forward messages to the .NET Framework tracing infrastructure, for any listeners registered to display diagnostic messages. To enable this, you add the following code to the web.config file:

<system.web>     <trace enabled="true" writeToDiagnosticsTrace="true" /> </system.web> 

New to ASP.NET 2.0, the writeToDiagnosticsTrace attribute defaults to false. Listeners that can receive any messages output to the ASP.NET trace context are those listed in the <trace> section under the <system.diagnostics> section.

The Trace Viewer

ASP.NET also supports application-level tracing through the trace viewer tool. Once tracing has been enabled for the application, each page request routes all the page-specific trace information to the viewer. You can view the trace viewer by requesting trace.axd from the root application directory. The trace viewer is shown in Figure 5-9.

image from book
Figure 5-9: The trace viewer ready for action.

To enable the viewer, you need to have a <trace> section in your application web.config file that is, the configuration file deployed in the root folder:

<configuration>     <system.web>         <trace enabled="true" />     </system.web> </configuration> 

The <trace> section supports a few attributes. The pageOutput attribute, for example, indicates whether the trace output should be visible to the individual pages too or accessible only through the viewer. By default, pageOutput is false and only the viewer receives trace information. However, each page can individually override this setting by using the Trace attribute on the @Page directive. The trace viewer caches no more than the number of requests specified by the requestLimit attribute (which is 10 by default).

In short, the ASP.NET trace viewer acts as a centralized console and gathers all the trace information generated by the pages in a certain application. Each request, up to the maximum number fixed by requestLimit, is identified by a row in the viewer's interface and can be consulted until the viewer's cache is cleared, as shown in Figure 5-10.

image from book
Figure 5-10: The trace viewer in action.

The trace viewer automatically tracks all requests and caches the full trace for each. When the request limit is reached, no other request will be cached until the log is manually cleared.

 


Programming Microsoft ASP. Net 2.0 Core Reference
Programming Microsoft ASP.NET 2.0 Core Reference
ISBN: 0735621764
EAN: 2147483647
Year: 2004
Pages: 112
Authors: Dino Esposito
BUY ON AMAZON

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