3. Writing Trace Information
The default trace log provides a set of important
information that can allow you to monitor some important aspects of
your application, such as the current state contents and the time taken
to execute portions of code. In addition, you'll often want to generate
your own tracing messages. For example, you might want to output the
value of a variable at various points in execution so you can compare
it with an expected value. Similarly, you might want to output messages
when the code reaches certain points in execution so you can verify
that various procedures are being used (and are used in the order you
expect). Once again, these are tasks you can also achieve using Visual
Studio debugging, but tracing is an invaluable technique when you're
working with a web application that's been deployed to a web server.
To write a custom trace message, you use the Write()
method or the Warn() method of the built-in Trace object. These methods
are equivalent. The only difference is that Warn() displays the message
in red lettering, which makes it easier to distinguish from other
messages in the list. Here's a code snippet that writes a trace message
when the user clicks a button:
Protected Sub cmdWrite_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles cmdWrite.Click
Trace.Write("About to place an item in session state.")
Session("Test") = "Contents"
Trace.Write("Placed item in session state.")
End Sub
These messages appear in the trace information
section of the page, along with the default messages that ASP.NET
generates automatically (see Figure 11).
You can also use an overloaded method of Write() or
Warn() that allows you to specify the category. A common use of this
field is to indicate the current method, as shown in Figure 12.
Protected Sub cmdWriteCategory_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles cmdWriteCategory.Click
Trace.Write("cmdWriteCategory_Click", _
"About to place an item in session state.")
Session("Test") = "Contents"
Trace.Write("cmdWriteCategory_Click", _
"Placed item in session state.")
End Sub
Alternatively, you can supply category and message
information with an exception object that will automatically be
described in the trace log, as shown in Figure 13.
Protected Sub cmdError_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles cmdError.Click
Try
DivideNumbers(5, 0)
Catch err As Exception
Trace.Warn("cmdError_Click", "Caught Error", err)
End Try
End Sub
Private Function DivideNumbers(ByVal number As Decimal, _
ByVal divisor As Decimal) As Decimal
Return number/divisor
End Sub
By default, trace messages are listed in the order
they were written by your code. Alternatively, you can specify that
messages should be sorted by category using the TraceMode attribute in
the Page directive:
<%@ Page Trace="True" TraceMode="SortByCategory" %>
or the TraceMode property of the Trace object in your code:
Trace.TraceMode = TraceMode.SortByCategory