Dela via


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

This walkthrough describes how to integrate ASP.NET tracing techniques with System.Diagnostics tracing techniques and write all trace messages to a single tracing output.

You can use tracing to track the flow of execution for your application, to display data at critical points during a Web form's life cycle, and to discover how the Web forms interact with various other components of your application. Using tracing, you can examine HTTP request parameters that are submitted to your application, how much memory is being stored in view state for a particular Web form, and other useful profiling information.

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

Common scenarios that use both ASP.NET tracing and the Trace class include Web pages that use middle-tier business objects to interact with data and business rules and 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 and monitoring the execution flow of the pages across the multiple tiers of your application using a single tracing output is desirable.

In this walkthrough you will work with tracing. You will modify a Web page and a business object to write trace messages, and then route all messages to one tracing output.

Tasks illustrated in this walkthrough include the following:

  • Creating a custom business component that can return data to a Web page. The component reads data from an XML file.

  • Creating a Web page that references the custom business object as a data source.

  • Enabling tracing for the Web page that is referencing the business object.

  • Writing trace messages to the Web page that is referencing the business object.

  • Writing Trace messages in a custom business object.

  • Configuring an ASP.NET application to write all trace messages to a single output.

  • Reading trace output.

Prerequisites

In order to complete this walkthrough, you need the following:

  • The Microsoft .NET Framework and an existing ASP.NET Web site.

Note

This walkthrough does not assume that you are using a designer, such as the Microsoft Visual Web Developer Web development tool or Microsoft Visual Studio.

Creating a Web Page and Business Object

In this walkthrough you will create the Default.aspx Web page, an AuthorClass business object, and the Authors.xml XML data file that is required for later steps in this walkthrough that involve tracing.

You can copy and paste the source code into files in your ASP.NET directory. This will create the Default.aspx Web page, AuthorClass business object, and Authors.xml file.

To create the Default.aspx page

  1. Open a text editor, such as Notepad, and create a new file.

  2. Enter the following code into the file.

    <%@ Page Language="VB" %>
    <html>
    <form runat="server">
        <asp:objectdatasource
          id="AuthorsObjectDataSource"
          runat="server"
          typename="PubsClasses.AuthorClass"
          selectmethod="GetAuthors"/>
    
        <asp:gridview
          id="GridView1"
          runat="server"
          datasourceid="AuthorsObjectDataSource" />
    </form>
    </html>
    
    <%@ Page Language="C#" %>
    <html>
    <form runat="server">
        <asp:objectdatasource
          id="AuthorsObjectDataSource"
          runat="server"
          typename="PubsClasses.AuthorClass"
          selectmethod="GetAuthors"/>
    
        <asp:gridview
          id="GridView1"
          runat="server"
          datasourceid="AuthorsObjectDataSource" />
    </form>
    </html>
    
  3. Save the file in the ASP.NET application root directory as Default.aspx.

The Default.aspx page uses a business object named AuthorClass to interact with XML data.

To create the AuthorClass business object

  1. Under the application root directory, create a directory named App_Code.

  2. In a text editor, such as Notepad, open a new file.

  3. Enter the following code into the file.

    Imports Microsoft.VisualBasic
    Imports System
    Imports System.Web
    Imports System.Data
    Namespace PubsClasses
        Public Class AuthorClass
            Private dsAuthors As DataSet = _
                New System.Data.DataSet("ds1")
            Private filePath As String = _
               HttpContext.Current.Server.MapPath("~/App_Data/authors.xml")
            Public Sub New()
                dsAuthors.ReadXml(filePath, Data.XmlReadMode.ReadSchema)
            End Sub
    
            Public Function GetAuthors() As DataSet
                Return dsAuthors
            End Function
        End Class
    End Namespace
    
    using System;
    using System.Web;
    using System.Data;
    namespace PubsClasses
    {
        public class AuthorClass
        {
            private DataSet dsAuthors = new DataSet("ds1");
            private String filePath =
                HttpContext.Current.Server.MapPath("~/App_Data/authors.xml");
    
            public AuthorClass()
            {
                dsAuthors.ReadXml (filePath, XmlReadMode.ReadSchema);
            }
    
            public DataSet GetAuthors ()
            {
                return dsAuthors;
            }
        }
    }
    
  4. In the App_Code directory, save the file as AuthorClass.cs (for C#) or AuthorClass.vb (for Microsoft Visual Basic).

The data file that the AuthorClass uses is Authors.xml.

To create the Authors.xml data file

  1. Under the application root directory, create a directory named App_Data.

  2. In a text editor, such as Notepad, open a new file.

  3. Enter the following XML data into the file.

    The XML file includes schema information that identifies the database structure of the data. This includes a primary-key constraint for the key.

    Note

    Business components can work with data in any way that is suited for your application. This walkthrough uses an XML file for convenience.

    <?xml version="1.0" standalone="yes"?>
    <dsPubs xmlns="http://www.tempuri.org/dsPubs.xsd">
    <xs:schema id="dsPubs" targetNamespace="http://www.tempuri.org/dsPubs.xsd" xmlns:mstns="http://www.tempuri.org/dsPubs.xsd" xmlns="http://www.tempuri.org/dsPubs.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified">
        <xs:element name="dsPubs" msdata:IsDataSet="true">
          <xs:complexType>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
              <xs:element name="authors">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="au_id" type="xs:string" />
                    <xs:element name="au_lname" type="xs:string" />
                    <xs:element name="au_fname" type="xs:string" />
                    <xs:element name="au_phone" type="xs:string" />
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:choice>
          </xs:complexType>
          <xs:unique name="Constraint1" msdata:PrimaryKey="true">
            <xs:selector xpath=".//mstns:authors" />
            <xs:field xpath="mstns:au_id" />
          </xs:unique>
        </xs:element>
      </xs:schema>
      <authors>
        <au_id>172-32-1176</au_id>
        <au_lname>White</au_lname>
        <au_fname>Gerry</au_fname>
        <au_phone>408 496-7223</au_phone>
      </authors>
      <authors>
        <au_id>213-46-8915</au_id>
        <au_lname>Green</au_lname>
        <au_fname>Marjorie</au_fname>
        <au_phone>415 986-7020</au_phone>
      </authors>
    </dsPubs>
    
  4. In the App_Data directory, save the file as Authors.xml, and then close it.

Adding Trace Messages to a Web page and Business Object

When you have created the Default.aspx page, the Authors.xml data file, and the AuthorClass business object, you can start working with tracing. Before you add any trace messages to your code, enable tracing for the Default.aspx page.

To enable tracing and display ASP.NET trace messages

  1. In a text editor, such as Notepad, open the Default.aspx page.

  2. Add a Trace attribute to the @ Page directive, and then set Trace to true.

    The declaration enables ASP.NET tracing for the Web page.

    For more information, see How to: Enable Tracing for an ASP.NET Page.

Page tracing is now enabled and when you view the page in a Web browser, you will see that the GridView control is followed by tracing output. The second tracing table that is displayed, Trace Information, shows you detailed information about the execution path for the Web page.

For more information about how to read the tracing output, see How to: View ASP.NET Trace Information with the Trace Viewer.

Writing Trace Messages

To better understand where some basic ASP.NET actions occur, such as the data binding that is performed by the GridView control in the Default.aspx page, add trace messages to the Web page and AuthorClass business object.

To write trace messages from a Web form

  • In your Default.aspx Web page, enter the following code after the @ Page directive but before the <html> tag.

    <script runat="server">
    
    Private Sub Page_Load(sender As Object, e As EventArgs)    
        Trace.Write("ASP.NET TRACE","page_load called.")
        Trace.Write("ASP.NET TRACE","page_load finished.")
    End Sub ' Page_Load
    
    </script>
    
    <script runat="server">
    private void page_load(object sender, EventArgs e) {
    
        Trace.Write("ASP.NET TRACE","page_load called.");
        Trace.Write("ASP.NET TRACE","page_load finished.");
    }
    </script>
    

    Note

    You might have to include a language attribute in your @ Page directive, depending on which language you use.

These trace messages are written to the ASP.NET trace output, and when you view the Default.aspx page again, you will see the trace messages in the Trace Information section, between "Begin Load" and "End Load". "Begin Load" and "End Load" are associated with the Page_Load method.

Now, you will add trace messages to the business object, AuthorClass.

To write trace messages to the AuthorClass business object

  1. Enter the following code into the AuthorClass constructor.

    System.Diagnostics.Trace.WriteLine("AuthorClass is created.", "AUTHORCLASS TRACE")
    
    System.Diagnostics.Trace.WriteLine("AuthorClass is created.", "AUTHORCLASS TRACE");
    
  2. Enter the following code into the AuthorClass.GetAuthors method.

    System.Diagnostics.Trace.WriteLine("GetAuthors called.","AUTHORCLASS TRACE")
    
    System.Diagnostics.Trace.WriteLine
    ("GetAuthors called.","AUTHORCLASS TRACE");
    

    Note

    When you use ASP.NET TraceContext..::.Write method, the trace category comes in front of the trace message in the parameter list for the method. However, when you use the .NET Framework tracing Write method, the trace message comes in front of the trace category.

If you compile the business object that has the TRACE compiler option, these trace messages are written to the system trace output. The trace messages are not written to the Default.aspx page, as the ASP.NET trace messages are. To test this, view the Default.aspx page and verify that only the same "ASP.NET TRACE" messages appear in the Trace Information table that you saw before.

In the next section, you will learn how to configure your ASP.NET Web application to automatically compile with the TRACE option enabled and to route all trace messages to the Web page.

Routing All Tracing Output to the Web Form

Routing the Trace messages that are contained in the AuthorClass business object to the ASP.NET trace output can show you when the AuthorClass is created and manipulated during request processing and give you a more holistic view of what your application is doing. To route Trace messages to an ASP.NET Web page, you must add a WebPageTraceListener object. You can add a trace listener either through configuration (recommended) or programmatically. For more information about adding a trace listener through configuration, see <listeners> Element for <trace>.

For the next procedure, you will need a Web.config file. If you already have a Web.config file, skip the next procedure and go to the following one, in which you will add a WebPageTraceListener object.

To create a Web.config file

  1. Open a text editor, such as Notepad, and create a new file.

  2. Enter the following text into the file.

    <!-- Web.Config Configuration File -->
    <configuration>
        <system.web>
            <customErrors mode="Off"/>
        </system.web>
    </configuration>
    
  3. Save the file in the same directory as Default.aspx as Web.config.

Next, you will add a WebPageTraceListener object to your application to route Trace messages to the ASP.NET tracing output.

To add a WebPageTraceListener for your application through configuration

  1. Open the Web.config file for your application.

  2. Place the following code in your Web.config file after the <system.web> section.

    <system.diagnostics>
      <trace>
        <listeners>
           <add name="WebPageTraceListener" 
                type="System.Web.WebPageTraceListener, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
        </listeners>
      </trace>
    </system.diagnostics>
    

    This configuration section adds a WebPageTraceListener object to the trace listeners collection for your application.

Adding a WebPageTraceListener using the configuration file for your application is the recommended method of adding a trace listener. However, you can also add the trace listener programmatically, which is especially useful, if you are using complex tracing logic and different types of trace listeners to trace your application, and the WebPageTraceListener is just one of many.

If you want to add a trace listener to your application programmatically, create a Global.asax file and add the listener by following these steps.

To create a Global.asax file and add a trace listener programmatically

  1. Open a text editor, such as Notepad, and create a new file.

  2. Enter following code into the file.

    <%@ Application Language="VB" %>
    <%@ Import Namespace="System.Web" %>
    
    <script runat="server">
      Sub Application_Start(sender As Object, e As EventArgs) 
        ' Code that runs when the application is started.
      End Sub
    
      Sub Application_End(sender As Object, e As EventArgs)
        ' Code that runs when the application shuts down.
      End Sub    
    </script>
    
    <%@ Application Language="C#" %>
    <%@ Import Namespace="System.Web" %>
    
    <script runat="server">
    
        void Application_Start(Object sender, EventArgs e) {
            // Code that runs when the application is started.
        }
    
        void Application_End(Object sender, EventArgs e) {
            // Code that runs when the application shuts down.
        }        
    </script>
    
  3. In your application root directory, save the file as Global.asax.

    This creates a basic Global.asax, which is a compiled module that contains code that runs whenever the application is started or stopped.

  4. Enter the following code into the Application_Start method of your Global.asax file.

    ' Create a trace listener for Web forms.
    Dim gbTraceListener As New WebPageTraceListener()
    ' Add the event log trace listener to the collection.
    System.Diagnostics.Trace.Listeners.Add(gbTraceListener)
    
    // Create a trace listener for Web forms.
    WebPageTraceListener gbTraceListener = new WebPageTraceListener();
    // Add the event log trace listener to the collection.
    System.Diagnostics.Trace.Listeners.Add(gbTraceListener);
    

    This programmatically adds a WebPageTraceListener to the trace listeners collection for your application.

  5. In the same directory as Default.aspx, save the file as Global.aspx.

With these steps, you have added a WebPageTraceListener to the trace listeners collection for the application. Although ASP.NET displays trace messages whenever tracing is enabled for a page, System.Diagnostics trace messages are written only when the code in which the trace messages reside is compiled by using an explicit compiler switch—the TRACE switch. In other words, if you do not explicitly compile the AuthorClass using the TRACE switch, you will not see the trace messages, even with the WebPageTraceListener added.

You can configure your application to automatically compile using the TRACE switch, by adding a new section to your Web.config file.

To compile your application automatically with trace enabled

  1. Open the Web.config file for your application.

  2. Place the following code into your Web.config file after the <system.diagnostics> section.

    <system.codedom>
      <compilers>
        <compiler language="c#;cs;csharp" 
                  extension=".cs" 
                  compilerOptions="/d:TRACE"
                  type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="1" />
        <compiler language="VB"
                  extension=".vb" 
                  compilerOptions="/d:Trace=true"
                  type="Microsoft.VisualBasic.VBCodeProvider, System,                                        Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </compilers>
    </system.codedom>
    

    By default, this configuration section makes your application compile all modules with the TRACE option.

If you view the Default.aspx page now, you will see both ASP.NET and System.Diagnostics trace messages. If the ASP.NET and System.Diagnostics trace messages do not appear, you might have to recompile the AuthorClass object.

From the trace information, you can see the AuthorClass object is created and its GetAuthors method is called during the PreRender method of the Web page life cycle. You can also see that there is a significant time lag when the AuthorClass object is created; the difference in time between the "Begin PreRender" message and the "AuthorClass is created." message is significant. This is because the AuthorClass opens the Authors.xml file and initializes its DataSet during creation, which is a relatively costly operation.

In the next section, you will learn how to configure your ASP.NET Web application to route all trace messages to the .NET Framework tracing output.

Routing All Tracing Output to .NET Framework Tracing

You might want to route ASP.NET tracing messages to the standard output for Trace messages, which can be a console window, disk, the Windows Event Log, or any other trace message output. You can enable this message routing in the Web.config configuration file.

To route all ASP.NET trace messages to the system tracing output

  1. Open the Web.config file for your application.

  2. Add a new attribute, writeToDiagnosticsTrace, to the trace element under <system.web>, and then set writeToDiagnosticsTrace to true.

        <system.web>
          <trace writeToDiagnosticsTrace="true"/>
          <customErrors mode="Off"/>
        </system.web>
    

    This configuration attribute instructs ASP.NET tracing to route ASP.NET trace messages to the standard system tracing output mechanism.

    To view the ASP.NET and System.Diagnostics trace messages in a context outside an ASP.NET page, use a TextWriterTraceListener object to write the trace messages to a file.

    The TextWriterTraceListener object must be configured to write to a specific file. You can do this using the initializeData attribute of the <add> element.

  3. Use the same steps that you followed to add the WebPageTraceListener object in the second procedure in "Routing All Tracing Output to the Web Form," earlier in this walkthrough, to add a TextWriterTraceListener object to your Web.config file and configure the TextWriterTraceListener to write to a file in the application root directory named Asptesttrace.log.

    Assuming that you did not add a WebPageTraceListener programmatically in the Global.asax file, the <system.diagnostics> section of the Web.config file will look similar to the following:

    <system.diagnostics>    
      <trace autoflush="true">
        <listeners>
          <add name="WebPageTraceListener" 
            type="System.Web.WebPageTraceListener, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
          <add name="TestTracer" 
            type="System.Diagnostics.TextWriterTraceListener, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
            initializeData="<app root directory>\Asptesttrace.log" />
        </listeners>
      </trace>
    </system.diagnostics>
    

    Note

    The initializeData attribute in the previous step has a placeholder value for the ASP.NET application root directory. If you try to a write trace messages to a file other than your application root directory, you might receive a security exception. By default, ASP.NET does not allow writing files to locations on disk that are outside the application root directory, such as C:\. Additionally, you might have to grant Write permission to the trace log for the ASP.NET worker process account.

    By default, you must wait to fill the trace buffer before trace data is written to the target stream.

  4. To see trace data in the trace log immediately after requesting your ASP.NET page, flush the buffer with every trace write by setting the autoflush attribute set to true as you did in the preceding step.

    The default value for the autoflush attribute is false.

  5. To flush the buffer of trace information programmatically, call the Flush method.

    Note

    For the business object that you developed in this walkthrough, if you call the Flush method in the Page_Load method and the autoflush attribute is false, the trace log will not show the trace data because the business object is rendered after the page Load event occurs.

Next Steps

This walkthrough illustrated how to work with ASP.NET and System.Diagnostics tracing features to route all trace messages a single output. You might want to experiment more with trace listeners and output and ASP.NET instrumentation features. For example, you might want to do the following:

  • Add an EventLogTraceListener object to your application.

    To do this, you would add an EventLogTraceListener object either programmatically or by using the configuration file that uses the same procedure as for the WebPageTraceListener. You can open the Event Log to review the trace messages that your application writes to the Event Log.

  • Change the business component to work with database data instead of with an XML file. You do not need to make any change to the controls on the page.

See Also

Tasks

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

Concepts

ASP.NET Tracing Overview