Thomas Alva Edison's light bulb VBInfoZine Home
   An ordinary VB developer shares his own successes and failures
   FREE to registered subscribers.  

ASP.NET Trace

Practical tips for using the ASP.NET Trace facility.

When handling errors in my ASP.NET applications, I've found it extremely useful to use the ASP.NET's Trace facility. It is exposed through the System.Web.HttpContext.Trace property and it contains methods for outputting messages to the ASP.NET trace log.

The ASP.NET's trace logging is controlled through the web.config file's <trace> element, and the log is viewable through the built-in trace.axd application (see links).

When handling events within my ASP.NET pages, I've made it a habit to insert a Try Catch block into every event handler method:

Private Sub Page_Load(...) Handles MyBase.Load
  Try
    ...
  Catch ex As Exception
    ' By using Warn the string will be RED in the 
    ' trace.axd output.
    Trace.Warn(ex.ToString()) 
  End Try
End Sub
In addition, I always deploy an ASP.NET .dll along with the corresponding .pdb file, because the stack trace (output by the Exception.ToString() method) then includes the source code file names and line numbers.

For Release builds, you'll have to enable generating the .pdb file - open the Project Properties dialog, expand the Configuration Properties node, click the Build node and check the Generate debugging information check box.

These two simple "tricks" helped me to identify problems in production applications quickly and easily.

Another simple trick:

Let's say you have a shared assembly that is used by ASP.NET as well as WinForms applications. You want to take advantage of the ASP.NET trace when the assembly runs within an ASP.NET application. No problem, just use the following code to check if your shared assembly is running within ASP.NET:

Public Sub MyTrace(ByVal msg As String)
  If System.Web.HttpContext.Current Is Nothing Then
    ' We're not running under ASP.NET, 
    ' use "ordinary" trace.
    System.Diagnostics.Trace.WriteLine(msg)
  Else
    ' We're under ASP.NET - use trace.axd.
    System.Web.HttpContext.Current.Trace.Write(msg)
  End If
End Sub

Links

Nothin' but ASP.NET - Tracing - all you need to know about ASP.NET tracing. Short, to the point.
 ©2003-2007 Palo Mraz. All Rights Reserved.   See my 'new browser window' policy