Lesson 3: Logging Exceptions

Lesson 3: Logging Exceptions

As you develop your application, it s a good idea to use exception logging to provide a means to track exceptions. An exception log is a list of handled exceptions that occur while your application is running. Reviewing the exception log periodically helps you verify that exceptions are being handled correctly, are not occurring too frequently, and are not preventing users from accomplishing tasks with your application.

In this lesson, you ll learn how to use the ASP.NET tracing features to implement exception logging in your Web application.

After this lesson, you will be able to

  • List the advantages of tracing as a way to record exceptions

  • Turn tracing on or off for an application or a Web form

  • Write messages to the trace log

  • View the trace log

  • Clear the trace log and get a new set of tracing information

Estimated lesson time: 20 minutes

Using Tracing to Log Errors

Tracing is a technique for recording events, such as exceptions, in an application. There have always been ways to record errors in an application usually by opening a file and writing error messages to it but tracing offers these significant advantages:

  • Standardization

    Building tracing into the .NET Framework ensures that programming techniques are the same across all the applications you develop with the .NET Framework.

  • Built-in Web support

    ASP.NET extends the .NET Framework tools by including information related to the performance and behavior of Web requests.

  • Configuration

    You can turn tracing on and off using settings in your application s configuration file. You don t have to recompile your application to enable or disable tracing.

  • Performance

    While disabled, tracing statements do not affect application performance.

To use tracing in a Web application, follow these steps:

  1. Turn tracing on.

  2. Write to the trace log.

  3. Read the trace log.

The following sections provide details on these three steps.

Turning Tracing On and Off

Tracing can be turned on or off for an entire Web application or for an individual page in the application:

  • To turn tracing on for an entire application, in the application s Web.config file, set the <trace> element s Enabled attribute to True.

  • To turn tracing on for a single page, set the DOCUMENT object s Trace property to True in the Visual Studio .NET Properties window. This sets the @ Page directive s Trace attribute to True in the Web form s HTML.

By default, trace output is displayed at the end of each Web page, as shown in Figure 6-7.

figure 6-7 tracing output

Figure 6-7. Tracing output

While this is fine for debugging purposes, you ll generally want to write trace output to a log file when you start testing your completed application. To write trace messages to a log file for an entire application, in the application s Web.config file, set the <trace> element s PageOutput attribute to False. ASP.NET then writes trace output to the Trace.axd file in your application s root folder.

The <trace> element also includes a RequestLimit attribute to specify how many page requests to write to the trace log. For example, the following line from a Web.config file turns on tracing for the application and writes the first 20 requests to the Trace.axd file:

<trace enabled="true" requestLimit="20" pageOutput="false" traceMode="SortByTime" localOnly="true" />

Writing trace messages to a log file does not affect tracing set at the page level. When the @ Page directive s Trace attribute is set to True, all trace messages for that page are displayed on the page.

To write trace messages to a log file for only selected pages in an application, follow these steps:

  1. In the application s Web.config file, set the <trace> element s Enabled attribute to True and PageOutput attribute to False.

  2. For each Web page you want to exclude from tracing, set the @ Page directive s Trace attribute to False.

When you have set the @ Page directive s Trace attribute to True or False, you can t restore the default setting from the Properties window in Visual Studio .NET. Instead, you must edit the Web form s HTML to remove the trace attribute from the @ Page directive. The following HTML shows the text to delete (in boldface):

Visual Basic .NET

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Trace.aspx.vb"  Inherits="MCSDWebAppsVB.Trace" trace="True" %>

Visual C#

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"  Inherits="MCSDWebAppsVB.Trace" trace="True"%>

Writing Messages to the Trace Log

The Trace object provides the Write and Warn methods to allow you to write messages to a request s trace information. The two methods are identical with one exception: messages written with Write are displayed in black, whereas messages written with Warn are displayed in red.

For example, the following code writes information about unhandled exceptions to the trace log using the Warn method, so they are displayed in red:

Visual Basic .NET

Private Sub Page_Error(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles MyBase.Error ' Write a message to the trace log. Trace.Warn("Error", "", Server.GetLastError()) ' Clear the error so the application can continue. Server.ClearError() ' Redisplay the page. Response.Redirect("Trace.aspx") End Sub 

Visual C#

private void Page_Error(object sender, System.EventArgs e) { // Write a message to the trace log. Trace.Warn("Error", "", Server.GetLastError()); // Clear the error so the application can continue. Server.ClearError(); // Redisplay the page. Response.Redirect("Trace.aspx"); }

The following code causes an unhandled exception when the user clicks butError:

Visual Basic .NET

Private Sub butError_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butError.Click Throw New System.IO.FileNotFoundException() End Sub

Visual C#

private void butError_Click(object sender, System.EventArgs e) { throw new System.IO.FileNotFoundException(); }

In some cases, you might want to take additional actions while tracing is enabled. For example, you might want to get specific user information to add to the trace message. The Trace object s IsEnabled property lets you run this code conditionally, so that it does not affect performance while tracing is disabled. For example, the following code adds browser information to the trace message if tracing is enabled:

Visual Basic .NET

Private Sub Page_Error(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles MyBase.Error If Trace.IsEnabled Then Dim strMessage As String If Request.Browser.AOL Then strMessage = "AOL Browser" Else strMessage = "Non-AOL Browser" End If Trace.Warn("Error", strMessage, Server.GetLastError()) End If Server.ClearError() Response.Redirect("Trace.aspx") End Sub

Visual C#

private void Page_Error(object sender, System.EventArgs e) { if (Trace.IsEnabled) { string strMessage; if (Request.Browser.AOL) strMessage = "AOL Browser"; else strMessage = "Non-AOL Browser"; // Write a message to the trace log. Trace.Warn("Error", strMessage, Server.GetLastError()); } // Clear the error so the application can continue. Server.ClearError(); // Redisplay the page. Response.Redirect("Trace.aspx"); }

Reading the Trace Log

By default, trace output is displayed at the bottom of each Web page for which tracing is enabled. As mentioned, if the <trace> element s PageOutput attribute is set to False in the Web.config file, trace output is written instead to the Trace.axd file in your application s root directory. You can view this file by simply navigating to it in your browser. For example, you could use the following hyperlink to open the log:

<A href="Trace.axd">View trace log.</A>

By default, you can view Trace.axd only from the local server running the application. If you want to view the trace log from a remote machine, such as when debugging remotely, set the <trace> element s LocalOnly attribute to False in the Web.config file, as shown here:

<trace enabled="true" requestLimit="20" pageOutput="false"  traceMode="SortByTime" localOnly="false" />

When you navigate to Trace.axd in a browser, the trace log appears as shown in Figure 6-8.

figure 6-8 the trace.axd log file

Figure 6-8. The Trace.axd log file

ASP.NET tracing stops after the server receives the number of HTTP requests entered in the <trace> element s RequestLimit attribute. To clear the list and start tracing again, click the Clear Current Trace link in the upper right corner of the Trace.axd page. The Clear Current Trace link redisplays Trace.axd and passes the query string clear=1 , as shown in the following HTML:

<a href="Trace.axd?clear=1">Clear trace log.</a>



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

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