Del via


ASP.NET Tracing Overview

ASP.NET tracing enables you to view diagnostic information about a single request for an ASP.NET page. ASP.NET tracing enables you to follow a page's execution path, display diagnostic information at run time, and debug your application. ASP.NET tracing can be integrated with system-level tracing to provide multiple levels of tracing output in distributed and multi-tier applications.

This topic contains:

  • Features

  • Background

  • Code Examples

  • Class Reference

Features

ASP.NET tracing offers the following features:

  • Debugging statments    You can write debug statements in your code without having to remove them from your application when it is deployed to production servers. You can also write variables or structures in a page and trace through the execution path of your page or application.

  • Integrated tracing functionality   You can route messages emitted by the System.Diagnostics.Trace class to ASP.NET tracing output, and route messages emitted by ASP.NET tracing to System.Diagnostics.Trace. You can also forward ASP.NET instrumentation events to System.Diagnostics.Trace. For more information, see Walkthrough: Integrating ASP.NET Tracing with System.Diagnostics Tracing.

  • Programmatic access to trace messages   You can access and manipulate trace messages from your code for finer control over the format of trace messages or for additional processing that you require.

  • Application-level tracing   The application-level tracing option lets you view the most recent tracing data available without restarting a tracing session and without increasing the amount of tracing data that the server must store. The most recent tracing data is displayed, and older tracing data is discarded.

Back to top

Background

Tracing appends diagnostic information and custom tracing messages to the output of the page and sends this information to the requesting browser. Optionally, you can view this information from a separate trace viewer (Trace.axd) that displays trace information for every page in an ASP.NET Web application. Tracing information can help you investigate errors or unwanted results while ASP.NET processes a page request.

You can configure individual pages to display trace information. Alternatively, you can configure the application's Web.config file so that all pages display trace information unless the page explicitly disables tracing. Setting application-level tracing is useful because you do not have to change individual pages to enable and disable it.

Trace statements are processed and displayed only when tracing is enabled. You can control whether tracing is displayed to a page, to the trace viewer, or both. For information about how to enable tracing for a page, see How to: Enable Tracing for an ASP.NET Page. For information about how to enable tracing for an application, see How to: Enable Tracing for an ASP.NET Application.

Application-Level ASP.NET Tracing

You enable application-level tracing by using the trace element in the Web.config file. When you enable application-level tracing, ASP.NET collects trace information for each request to the application, up to the maximum number of requests you specify. The default number of requests is 10. By default, when the trace viewer reaches its request limit, the application stops storing trace requests. You can configure tracing to store the oldest tracing data (discarding newer items) or the most recent trace information (discarding older items).

Note

When you enable tracing for the whole application in the Web.config file, trace information is gathered and processed for each page in that application. To override the application-wide settings, set the Trace attribute in that page's @ Page directive to false. Any Write or Warn statements that you include in a page's code are stored and returned to the trace viewer only.

Viewing Trace Information

You can view trace information at the bottom of individual pages. Alternatively, you can use the trace viewer (Trace.axd) to view trace information that is collected and cached by ASP.NET when tracing is enabled. For details about what the trace display includes, see Reading ASP.NET Trace Information later in this topic.

If you want trace information to appear at the end of the page that it is associated with, you can set the trace element's PageOutput attribute to true. If you enable application-level tracing, but you do not want trace information displayed for some pages, you can set the Trace attribute in those pages' @ Page directive to false. For more information about how to configure an ASP.NET application, see ASP.NET Configuration Overview.

By default, application-level tracing can be viewed only on the local Web server computer. To make application-level trace information visible from remote computers, you can set the trace element's LocalOnly attribute to false.

Note

To help keep the Web application secure, use the remote tracing capability only when you are developing or deploying your application. Make sure that you disable it before you transfer your application to production Web servers. To do this, set the LocalOnly attribute to true in the Web.config file.

The following example shows an application trace configuration that collects trace information for up to 40 requests. It also enables browsers on computers other than the server to display the trace viewer.

<configuration>
  <system.web>
    <trace enabled="true" requestLimit="40" localOnly="false" />
  </system.web>
</configuration>

Writing Custom ASP.NET Trace Messages

You can append custom trace information to the trace display in an ASP.NET page or to the trace log. The trace information that is written to the trace log is viewable with the trace viewer. For more information, see How to: View ASP.NET Trace Information with the Trace Viewer.

You can write trace information by using the TraceContext class's Warn or Write methods. The difference between the two methods is that a message written with the Warn method appears in red text.

The following example shows how to use the TraceContext class to display trace information at the end of an ASP.NET page. A different exception is thrown for each LinkButton control that caused the postback. The error message that is used to initialize the ArgumentException or InvalidOperationException instance is displayed in the trace log.

<%@ Page Language="VB" Trace="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    Try
      If (IsPostBack) Then

        Select Case Request.Form("__EVENTTARGET")
          Case "WarnLink"
            Throw New ArgumentException("Trace warn.")
          Case "WriteLink"
            Throw New InvalidOperationException("Trace write.")
          Case Else
            Throw New ArgumentException("General exception.")
        End Select  
      End If
    Catch ae As ArgumentException
      Trace.Warn("Exception Handling", "Warning: Page_Load.", ae)
    Catch ioe As InvalidOperationException
      Trace.Write("Exception Handling", "Exception: Page_Load.", ioe)
    End Try
  End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Trace Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:LinkButton id="WriteLink" 
                      runat="server"
                      text="Generate Trace Write" />
      <asp:LinkButton id="WarnLink"
                      runat="server"
                      text="Generate Trace Warn" />
    </div>
    </form>
</body>
</html>
<%@ Page Language="C#" Trace="true"  %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">
void Page_Load(object sender, EventArgs e)
{
    try {
      if (IsPostBack)
      {

        switch (Request.Form["__EVENTTARGET"])
        {
          case "WarnLink":
            throw new ArgumentException("Trace warn.");
            break;
          case "WriteLink":
            throw new InvalidOperationException("Trace write.");
            break;
          default:
            throw new ArgumentException("General exception.");
            break;          
        }
      }
    }
    catch (ArgumentException ae) {    
        Trace.Warn("Exception Handling", "Warning: Page_Load.", ae);
    }
    catch (InvalidOperationException ioe) {    
        Trace.Write("Exception Handling", "Exception: Page_Load.", ioe);
    }
}

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Trace Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:LinkButton id="WriteLink" 
                      runat="server"
                      text="Generate Trace Write" />
      <asp:LinkButton id="WarnLink"
                      runat="server"
                      text="Generate Trace Warn" />
    </div>
    </form>
</body>
</html>

Reading ASP.NET Trace Information

You can view trace information that is appended at the end of an ASP.NET page or in the trace viewer. In both cases, the information displayed is the same. ASP.NET organizes the trace information in a series of tables. For information about how to view trace information in a page, see How to: Enable Tracing for an ASP.NET Page. For information about how to view trace information in the trace viewer, see How to: View ASP.NET Trace Information with the Trace Viewer.

Trace information appears in the following order.

Request Details

The Request Details section displays general information about the current request and response.

Value

Description

Session ID

The session identification for the specified request.

Time of Request

The time that the request was made.

Request Encoding

The character encoding for the request.

Request Type

The HTTP method (GET or POST).

Status Code

The status-code value associated with the response. For more information, see RFC 2616 at the World Wide Web Consortium (W3C) Web site.

Response Encoding

The character encoding for the response.

Trace Information

The Trace Information section displays the flow of page-level events. If you have created custom trace messages, the messages are displayed in the Trace Information section also.

Value

Description

Category

The custom trace category specified in a Warn or Write method call, if any.

Message

The custom trace message specified in a Warn or Write method, if any.

From First(s)

The elapsed time in seconds since the first trace message was processed. The first trace message appears at the top of the list.

From Last(s)

The elapsed time in seconds between the processing of the current trace message and the previous trace message.

Control Tree

The Control Tree section displays information about ASP.NET server controls that are created in the page.

Value

Description

Control ID

The identification for the control. If you have not specified an ID property for the control, ASP.NET generates an ID by using the UniqueID property.

Type

The fully qualified type of the control.

Render Size bytes

The size in bytes of the rendered control (including child controls). This is the size of the actual HTML, XML, or other format that is sent to the browser.

ViewState Size bytes

The size in bytes of the control's view state (excluding child controls). For more information, see ASP.NET State Management Overview.

ControlState Size bytes

The size in bytes of the control's control state (excluding child controls). For more information, see ASP.NET State Management Overview.

Session State

The Session State section displays information about values that are stored in Session state, if any. For more information, see ASP.NET Session State Overview.

Value

Description

Session Key

The key for data stored in session state, if any.

Type

The fully qualified type of the object that stores the data.

Value

A string representation of the data stored in session state, if any.

Application State

The Application State section displays information about values stored in Application state, if any. For more information, see ASP.NET Application State Overview.

Value

Description

Application Key

The key for data stored in application state, if any.

Type

The fully qualified type of the object that stores the data.

Value

A string representation of the data that is stored in application state, if any.

Cookies Collection

The Request Cookies and Response Cookies sections display information about the cookies that are passed between the browser and the server on each request and response. The section displays both persistent and session cookies. ASP.NET creates some cookies automatically, such as those for cookie-based Session state and for forms authentication. For more information, see ASP.NET Cookies Overview.

Value

Description

Name

The name of the cookie.

Value

The value of the cookie, or of subkeys and values if the cookie is multivalued.

Size

The size in bytes of the cookie.

Headers Collection

The Headers Collection section displays information about request and response message header name/value pairs, which provide information about the message body or requested resource. Header information is used to control how request messages are processed and how response messages are created. For more information about HTTP headers, see RFC 2616 at the World Wide Web Consortium (W3C) Web site.

Value

Description

Name

The name of the header.

Value

The value of the header.

Form Collection

The Form Collection section displays name/value pairs that show the form element values (control values) that are submitted in a request during a POST operation (postback).

Value

Description

Name

The name of the form variable.

Value

The value of the form variable.

Querystring Collection

The Querystring Collection section shows the values that are passed in the URL. In a URL, query string information is separated from the path information by a question mark (?); multiple query string elements are separated by an ampersand (&). Query string name/value pairs are separated by an equal sign (=). The QueryString property of the HttpRequest object returns a NameValueCollection of query string variables.

Value

Description

Name

The name of the query string variable.

Value

The value of the query string variable.

Server Variables

The Server Variables section displays a collection of server-related environment variables and request header information. The ServerVariables property of the HttpRequest object returns a NameValueCollection of server variables.

Value

Description

Name

The name of the server variable.

Value

The value of the server variable.

Back to top

ASP.NET Tracing and Diagnostics Tracing

ASP.NET tracing writes messages that are displayed on ASP.NET Web pages and the ASP.NET Trace viewer (Trace.axd). In contrast, the System.Diagnostics.Trace class is used to trace write messages to the standard .NET Framework trace output (typically a console window). To make it easier to track how your ASP.NET Web pages interact with business objects and other components, you can integrate ASP.NET tracing output with System.Diagnostics tracing. You can then route all tracing messages to one of these outputs.

A common scenario that uses both ASP.NET tracing and System.Diagnostics.Trace is Web pages that use middle-tier business objects to interact with data and business rules. You can also use System.Diagnostics.Trace tracing for pages that use enterprise services such as transactions and queues. In these situations, the business and enterprise components play key parts in the successful execution of the page. In addition, it can help with application analysis to monitor execution flow across the multiple tiers by using a single tracing output. For more information, see How to: Enable Tracing for an ASP.NET Application.

Trace Configuration Attributes

The following table shows the attributes that you can use to modify the behavior of application-level tracing in the trace element of the Web.config file.

Attribute

Description

Enabled

true to enable tracing for the application; otherwise, false. The default is false. You can override this setting for individual pages by setting the Trace attribute in the @ Page directive of a page to true or false.

PageOutput

true to display trace both in pages and in the trace viewer (Trace.axd); otherwise, false. The default is false.

Note

Individual pages that have tracing enabled are not affected by this setting.

RequestLimit

The number of trace requests to store on the server. The default is 10.

TraceMode

The order in which trace information is displayed. Set to SortByTime to sort by the order in which information was processed. Set to SortByCategory to sort alphabetically by user-defined category. The default is SortByTime.

LocalOnly

true to make the trace viewer (Trace.axd) available only on the host Web server; otherwise, false. The default is true.

MostRecent

true to display the most recent trace information as tracing output; otherwise, false. If this value is false, when the requestLimit value is exceeded, new requests are not stored. The default is false.

Note

Tracing data that exceeds the limit defined by the requestLimit attribute is discarded in favor of the most recent data only when mostRecent is true.

Code Examples

How to and Walkthrough Topics

How to: Enable Tracing for an ASP.NET Page

How to: Enable Tracing for an ASP.NET Application

How to: View ASP.NET Trace Information with the Trace Viewer

Walkthrough: Integrating ASP.NET Tracing with System.Diagnostics Tracing

Back to top

Class Reference

Class

Description

System.Diagnostics.Trace

The main class for implementing tracing.

TraceContext

Captures and presents execution details about a Web request.

Back to top

See Also

Concepts

Performance, Troubleshooting, and Debugging

Reference

Back to top