ASP.NET Tracing



ASP.NET Tracing

Implement tracing: Display trace output.

Log test results: Control debugging in the Web.config file.

In addition to the Trace and Debug classes, ASP.NET supports one more method for tracing, which is specially designed for Web applications and Web services. This method of tracing is called ASP.NET tracing.

With the help of ASP.NET tracing, you can view trace messages and diagnostics information of a Web request along with the page output or through a separate trace viewer utility (trace.axd). You can write custom trace messages by using the System.Web.TraceContext class. The TraceContext class is responsible for gathering execution details of a Web request. You can access the TraceContext object for the current request through the Trace property of the Page class. After you have the TraceContext object, you can invoke its member methods to write trace messages to the trace log. Figure lists some important members of the TraceContext class with which you should be familiar.

Figure Important Members of TraceContext Class

Member

Type

Description

IsEnabled

Property

Specifies whether tracing is enabled for a request.

TraceMode

Property

Indicates the sort order in which the messages should be displayed. It can have one of three values—Default, SortByCategory, and SortByTime.

Warn()

Method

Writes the messages to the trace log in red, which indicates that they are warnings. It has three overloads—one with the message, one with the category and message, and the last one with the category, message, and exception object.

Write()

Method

Writes the messages in the trace log. It has three overloads, just like the Warn() method.

NOTE

Tracing Beyond a Page The Page class exposes the Trace property to get access to the TraceContext object. If you want to write messages from outside the page (such as from the global.asax file or from the custom server controls) you can access the Trace property of the HttpContext object via the Control.Context or HttpContext.Current property.


By default, tracing is not enabled. Thus, the trace messages and diagnostics information are not displayed. In the following sections I'll show you how to enable tracing at the page level as well as the application level.

EXAM TIP

IsEnabled Property The IsEnabled property can be dynamically assigned to turn tracing for a page on or off. It can also be used to include or exclude code based on the trace setting for a page.


ASP.NET Page-Level Tracing

You can enable tracing for a Page by using the Trace attribute of the Page directive. When the Trace attribute is set to true in the Page directive, the page appends the tracing information of the current Web request with its output. You can also enable tracing by setting the DOCUMENT object's Trace property to true. Step-by-Step 9.5 demonstrates how to enable tracing in a page and write trace messages in to the trace log.

STEP BY STEP

9.5 Using the TraceContext Class to Display Debugging Information in a Web application

  1. Add a new Visual C# ASP.NET Web application named StepByStep9_5 to the solution.

  2. Add a new Web form to the project. Name the Web form FactorialCalculator.aspx.

  3. Place two TextBox controls (txtNumber and txtFactorial), three Label controls (one with the ID lblHeading), and a Button control (btnCalculate) on the Web form and arrange the controls as shown in Figure.

    11. Design of a form that calculates the factorial of a given number.

    graphics/09fig11.jpg

  4. Switch to HTML view of the form in the designer. Add the trace="true" attribute to the Page directive:

    
    <%@ Page language="c#"
    
             Codebehind="FactorialCalculator.aspx.cs"
    
             AutoEventWireup="false"
    
             Inherits="StepByStep9_5.FactorialCalculator"
    
             Trace="true"%>
    
    
  5. Double-click the Button control and add the following code to the event handler to handle the Click event:

    
    private void btnCalculate_Click(
    
        object sender, System.EventArgs e)
    
    {
    
        // write a trace message
    
        Trace.Write("Factorial",
    
             "Inside Button Click event handler");
    
        int intNumber;
    
        try
    
        {
    
            intNumber = Convert.ToInt32(txtNumber.Text);
    
        }
    
        catch (Exception ex)
    
        {
    
            Trace.Warn("Factorial", "Invalid value", ex);
    
    
    
            return;
    
        }
    
        if(intNumber < 0)
    
        {
    
            Trace.Warn("Factorial",
    
                "Invalid negative value");
    
        }
    
        int intFac = 1;
    
        for (int i = 2; i <= intNumber; i++)
    
        {
    
            intFac = intFac * i;
    
            Trace.Write("Factorial", "Value of i: " + i);
    
        }
    
        if(intFac < 1)
    
            Trace.Warn("Factorial" ,
    
                "There was an overflow");
    
    
    
        txtFactorial.Text = intFac.ToString();
    
        Trace.Write("Factorial" ,
    
            "Done with computations, returning...");
    
    }
    
    
  6. Set project StepByStep9_5 as the startup project. Set the Web form as the start page for the project.

  7. Run the project. Notice that the Web page displays a wide range of information after its general output. Enter a value into the number text box and click the Calculate button. You will see the factorial value displayed in the factorial text box, along with some trace messages in the Trace Information section of the trace log, as shown in Figure.

    Figure. You can view the trace log along with a page's output by setting the trace attribute of the Page directive to true.

    graphics/09fig12.jpg

  8. Try entering a negative value, or a larger value such as 100, and notice the trace messages displayed in the trace log. You should see that the warning messages are displayed in red.

As you can see, when tracing is enabled, ASP.NET displays a great amount of information related to the request, in addition to the trace messages written by you. The information is grouped in different tables:

  • Request Details— Includes the session identifier, the time the request was made, the request character encoding, the type of HTTP request (GET or POST), the HTTP response status code, and the response character encoding.

  • Trace Information— Includes the messages and warnings generated by the ASP.NET engine or generated by you making calls to the Write() or Warn() methods of the TraceContext class. It displays the information in four columns—the category of the message, the trace message, seconds since the first trace message was displayed, and seconds since the most recent trace message was displayed.

  • Control Tree— Includes the entire collection of controls in the ASP.NET page hierarchically. The information is displayed in four columns—the control identifier, the fully qualified type of the control, the size (in bytes) of the rendered control including its child controls, and the size (in bytes) of the view state of the control excluding its child controls.

  • Session State— Includes the session state only if any data is stored in the session. The table displays the session key, the fully qualified type of the session data stored, and the value of the session data.

  • Cookies Collection— Includes the cookies associated with the application. The information displayed is the cookie's name, value, and size.

  • Headers Collection— Includes the HTTP headers passed to the Web page. It displays the header's name and its value.

  • Form Collection— Includes the form collection. It is displayed only if a Web form is defined in the page and the form is posting back from the server. It displays the name of the control that's in the form and its value.

  • Querystring Collection— Includes the query string collection only if any query string parameters are passed during a request for the page. It displays the name of the query string parameter and its value.

  • Server Variables— Includes all the server variables associated with the page. It displays the name of the server variable and its value.

As apparent from the preceding list, the trace log definitely helps a great deal with understanding the program's execution path. It provides information about state, performance, and the structure of page controls. This information can be of great help in debugging and improving the quality of the program.

ASP.NET Application-Level Tracing

You can enable tracing for an entire application by using the application configuration web.config file in the application's root directory. Enabling tracing through the web.config file allows you to view the trace information by using the trace viewer in a separate page instead of displaying it with the page output. The <trace> element is used to configure tracing for an application. The attributes of the <trace> element are element;attributes>

  • enabled— Indicates whether tracing is enabled for an application. If enabled, you can use the trace viewer to view trace information.

    EXAM TIP

    Page-Level Tracing Overrides The page-level trace setting overrides the trace setting for the application. For example, if pageOutput is set to false in the web.config file and if the trace attribute is enabled at the page level, the trace information is still displayed along with the page output.


  • localOnly— Indicates whether the trace viewer can be viewed by only the local client (running on the Web server itself) or by any client.

  • pageOutput— Indicates whether the trace information should be displayed along with the page output.

  • requestLimit— Indicates the number of requests whose trace information should be stored on the server. Tracing gets disabled when the request limit is reached.

  • traceMode— Indicates the order in which the trace messages should be displayed in the Trace Information section of the trace log. It can be either SortByCategory (sorted by the Category column) or SortByTime (sorted by the First(s) column).

Thus, when tracing is enabled for an application, you can use the trace viewer to view requests for each page (unless a page has its Page directive's trace attribute set to false). Trace viewer can be viewed by navigating to trace.axd from any directory in an application. You should notice that there is no trace.axd file in the application directory structure. Instead, this request is handled by the TraceHandler object defined in the <httpHandlers> element of the machine.config file. Trace viewer lists all the page requests in an application along with the time of request, the filename, HTTP status code, type of request, and a link to view the request's trace log. It also contains a link to clear the current trace information of all page requests.

Step-by-Step 9.6 demonstrates how to set application-level tracing.

STEP BY STEP

9.6 Setting Application-Level Tracing for a Web Application

  1. Open the web.config file of the Web application StepByStep9_5 from the Solution Explorer. Modify the <trace> element defined in the <system.web> element with the following code:

    
    <trace
    
        enabled="true"
    
        requestLimit="10"
    
        pageOutput="false"
    
        traceMode="SortByTime"
    
        localOnly="true"
    
          />
    
    
  2. Remove the trace="true" attribute from the Page directive of the form FactorialCalculator.aspx.

  3. Run the project. Notice that there is no trace information along with the page display. Enter a value into the number text box and click the Calculate button. You will see the factorial value displayed in the factorial text box.

  4. Now navigate to trace.axd under your application directory by typing http://localhost/StepByStep9_5/Trace.axd (substitute the name of your Web server to localhost if the Web server is not on your development computer). Notice the Application Trace page as shown in Figure.

    13. Trace viewer displays all the page requests in the Application Trace page.

    graphics/09fig13.jpg

  5. Click the View Details link in the second row (the one with the post request). The entire trace log for that page request is displayed as shown in Figure.

    Figure. You can view the complete trace log of a page request by using the trace viewer utility (trace.axd).

    graphics/09fig14.jpg

  6. Now open the web.config file and change the pageOutput attribute to true. Run the project. Enter a value into the number text box and click the Calculate button. You should see the factorial value being displayed in the factorial text box, along with the entire trace log being appended to the trace output. You can also view the trace log with the help of the trace viewer, as shown in steps 4 and 5.

  7. Now open the form in HTML view in the designer. Add the trace="false" attribute in the Page directive. Run the project. Enter a value into the number text box and click the Calculate button. You should see the factorial value being displayed in the factorial text box. Notice that neither the page output nor the trace viewer displays the trace information. The page level directive overrides the settings in the web.config file.

REVIEW BREAK

  • The System.Web.TraceContext class can be used to display trace messages in a Web application. You can easily view these messages by using the trace viewer utility or at the end of the page output. ASP.NET displays various page request details, along with custom trace messages displayed by you.

  • To enable ASP.NET tracing for each page, set the trace attribute of the Page directive to true.

  • ASP.NET tracing also can be enabled at the application level by setting the enabled attribute of the <trace> element to true in the application-wide web.config file.