Tracing


Tracing is the art of tracking the progress of an application “ finding out what's happening and when. It is a safe bet to use tracing “ scattering Response.Write statements through your code. It may not be elegant, but it works. There are, however, problems with this approach:

  • Where to output the tracing information?

    Putting it inline just makes the output hard to read and the trace statements hard to interpret. Ways of getting around this are to build a string of tracing information, and then output that as the last thing on the page, or write the tracing information externally (such as to a text file, database or event log).

  • How to enable or disable tracing?

    There are two ways to achieve this in ASP. The first is the laborious method of just commenting out the tracing information. This is time consuming, not very flexible, and error-prone (ever commented out too many lines?). The second approach is to encapsulate the tracing within a procedure in an include file. You can then just comment out the code in one place, or replace the procedure with one that does nothing, but this is also inefficient. Alternatively, you can use a switch (perhaps a registry setting or configuration file) to identify whether tracing is enabled, but, again, this can lead to performance problems.

  • How to have tracing, but not have it visible to users?

    When testing applications, you often want to trace the path of execution without your users being aware of the information. Writing output to a text file or database would probably be the best solution here.

You can actually create some quite elegant solutions for tracing, but with ASP.NET, everything is neatly encapsulated for you. What's particularly cool is that you can decide if you want tracing managed on a page-by-page basis, or for the entire application.

Page-Level Tracing

Page-level tracing is achieved by adding a page-level directive. For example, consider the following page (called SimpleTrace.aspx ):

  <html>   <body>   This is a simple page showing tracing in action.   <br/>   At the moment the page does nothing.   <br/>   </body>   </html>  

It doesn't do anything, and you can see there are just a couple of lines of text. To enable tracing for this page, set the Trace attribute of the Page directive to True :

  <%@ Page Trace="True" %>  

Adding this to the top of your ASP.NET page will give you the output shown in Figure 22-1:

click to expand
Figure 22-1:

This information is all automatically generated and added to the bottom of the page, and consists of the following sections (not all of which are shown in Figure 22-1, purely due to the screen size ):

Section

Contains

Request Details

Information about the request, such as the type, HTTP code.

Trace Information

Details of execution order, showing the time taken to execute for each section. When adding your own custom message (you will see how to do that in a short while), they will appear in this section.

Control Tree

Hierarchical list of all controls on the page, including their size.

Session State

Details of each item (if any) held in Session state.

Application State

Details of each item (if any) held in Application state.

Cookies Collection

Details of each cookie.

Headers Collection

The HTTP headers.

Forms Collection

Name and value of each Form variable.

QueryString Collection

Name and value (if applicable ) of each QueryString variable.

Server Variables

A complete list of all server variables and their contents.

Note

Not all sections appear for all pages. For example, if your page doesn't contain Form or QueryString information, these sections are not rendered.

Writing Trace Information

To add your own trace information to the Trace Information section you can use the TraceContext object, made available through the Trace property of a page. For example, if you add the following to your simple page:

  <script language="VB" runat="server">     Sub Page_Load(Sender As Object, E As EventArgs)   Trace.Write("Page_Load", "Here we are")   End Sub     </script>  

Upon refreshing the page, the trace information now looks like Figure 22-2:

click to expand
Figure 22-2:

You can see that your line of text has been added. If you now add a button to the page, such as:

  <form runat="server">     <asp:Button id="btn" Text="Click Me!" OnCLick="btn_Click" runat="server"/>   <br/>   <asp:Label id="foo" runat="server"/>     </form>  

And have the following as the event:

  Sub btn_Click(Sender As Object, E As EventArgs)     Trace.Warn("btn_Click", "Button was pressed")     End Sub  

Upon postback you will see Figure 22-3:

click to expand
Figure 22-3:

The new line has been added in red because you used the Warn method (trust me “ it really is red!), and you can see the extra events that are called as part of the postback. Using Warn method allows you to easily spot lines in the trace information.

The TraceContext Object

Tracing is actually handled by the TraceContext object, which has two properties and two methods :

Property/Method

Description

IsEnabled

Indicates whether or not tracing is enabled, and equates to the page-level directive. This is a read/write property, so it can be used to enable or disable tracing from within code.

TraceMode

Indicates the sort order of messages in the Trace Information section, and can be either SortByCategory or SortByTime . Like IsEnabled , this is also available through a page-level directive.

Write

Writes information to the Trace Information section.

Warn

The same as Write , except that the text is shown in red.

Both methods for writing to the log can be overloaded:

  Trace.Write (  message  )   Trace.Write (  category  ,  message  )   Trace.Write (  category  ,  message  ,  exceptionInfo  )   Trace.Warn (  message  )   Trace.Warn (  category  ,  message  )   Trace.Warn (category, message, exceptionInfo)  

The three parameters are as follows :

Parameter

Type

Description

category

String

The category for the message

message

String

The message to display

exceptionInfo

System.Exception

Any exception information, to be displayed after the message

The following code example shows all three parameters in action. The first two with the Write method and the third with the Warn method:

  Trace.Write("A simple message")   Trace.Write("Button", "Message here")   Try   ' some code goes here   Catch E As Exception   Trace.Warn("Error", "Message here", E)   End Try  

Turning Off Tracing

One of the problems with the old ASP method of tracing was that you had to remove the trace statements when you were done. With ASP.NET, all you do is turn off tracing either by setting the page directive or using the IsEnabled property. You don't have to remove the Trace statements themselves , or comment them out, because if tracing isn't enabled, the compiler automatically removes them. So, this is where the great improvement comes “ you are free to put as many trace statements into your code as you feel is warranted, without the worry of having to clean them up after testing, and without worrying about performance.

You can even make the tracing dynamic , perhaps by use of the query string. For example, consider the following code:

  Sub Page_Load(Sender As Object, E As EventArgs)   If Request.QueryString("Trace") = "True" Then   Trace.IsEnabled = True   End If   End Sub  

You could then call a page with http://localhost/TestPage.aspx?Trace=True, which would turn on tracing, but if called normally, no tracing would appear. Alternative solutions such as using the registry or a configuration file to identify whether tracing is enabled are also possible.

Tracing from Components

The same method of tracing is available to components called from an ASP.NET page, allowing them to integrate seamlessly with your pages. To access the Trace functionality, you have to import the System.Web namespace, reference the current HttpContext object, and get its Trace property. For example:

  Imports System   Imports System.Web   Namespace People   Public Class PersonTrace   Private ctx As HttpContext   Public Sub New()   ctx = HttpContext.Current   ctx.Trace.Write("PersonTrace", "New")   End Sub  

These messages just become part of the existing trace messages, appearing in the order in which they are called. See Figure 22-4:

click to expand
Figure 22-4:
Note

Tracing output is only displayed if tracing is turned on for the page in which the component is called.

Application-Level Tracing

Application-level tracing expands on the page idea, but allows tracing to be controlled for an entire application. To configure this option, you need to create, or edit, the web.config file in the root directory of your application. Application-level tracing works by collecting the trace information for each request, which can be optionally displayed in each page, or just collected for later examination. You can add a Trace element as part of the <system.web> section. It takes the following attributes:

Attribute

Default

Description

enabled

False

Indicates whether or not application-level tracing is enabled.

requestLimit

10

The number of HTTP requests for which to store tracing information in the trace log. This works on a rolling system, where the last requests are kept.

pageOutput

False

Indicates whether or not the tracing information is displayed at the end of each page. The information is still collected whether or not it is displayed.

traceMode

SortByTime

Indicates the sort order of messages in the Trace Information section, and can be either SortByCategory or SortByTime .

localOnly

True

Indicates whether the trace information is only shown to local clients, or is available to remote clients as well.

The interesting thing about application-level tracing is that the trace details are collected for each request (up to the number set in the requestLimit attribute), irrespective of whether they are shown on the page. This means that tracing can be enabled for a live application without the users seeing anything.

Important

Page-level tracing overrides application-level tracing. Therefore, if your page has a Trace attribute, application tracing will not work for that page.

To view the trace information, navigate to trace.axd held in the root directory of the application. This file doesn't actually exist, but is instead a special URL that is intercepted by ASP.NET. It will give you a list of requests as seen in Figure 22-5:

click to expand
Figure 22-5:

Clicking on the View Details link for a request will show the same trace details that would normally be shown at the end of each page.




Professional ASP. NET 1.1
Professional ASP.NET MVC 1.0 (Wrox Programmer to Programmer)
ISBN: 0470384611
EAN: 2147483647
Year: 2006
Pages: 243

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