|
Trace Logging to Page Output
Page-level tracing enables you to write debugging statements directly to a page's output, and conditionally run debugging code when tracing is enabled. To enable tracing for a page, include the following directive at the top of the page code:
<%@ Page Trace="true"%> <%@ Page Trace="true" TraceMode="SortByCategory" %> The following example shows the default output when page-level tracing is enabled. Note that ASP.NET inserts timing information for important places in the page's execution lifecycle:
The page exposes a Trace property (of type TraceContext), which can be used to output debugging statements to the page output, provided tracing is enabled. Using TraceContext, you can write debugging statements using the Trace.Write and Trace.Warn methods, which each take a message string or a category and message string. Trace.Warn statements are identical to Trace.Write statements, except they are output in red.
' Trace(Message)
Trace.Write("Begging User Code...")
...
Trace.Warn("Array count is Nothing!")
' Trace(Category, Message)
Trace.Write("Custom Trace","Beginning User Code...")
...
Trace.Warn("Custom Trace","Array count is null!")
VB
When tracing is disabled (that is, when Trace="false" on the Page directive, or is not present), these statements do not run and no Trace output appears in the client browser. This makes it possible to keep debugging statements in production code and enable them conditionally at a later time. Often you might need to run additional code to construct the statements to pass to the Trace.Write or Trace.Warn methods, where this code should only run if tracing is enabled for the page. To support this, Page exposes a Boolean property, Trace.IsEnabled, which returns true only if tracing is enabled for the page. You should check this property first to guarantee that your debugging code can only run when tracing is on.
If Trace.IsEnabled Then
For i=0 To ds.Tables("Categories").Rows.Count-1
Trace.Write("ProductCategory",ds.Tables("Categories").Rows(i)(0).ToString())
Next
End if
VB
The following example shows the use of Trace.Write and Trace.Warn to output debugging statements. Also note the use of the Trace.IsEnabled property to conditionally run extra debugging code. In this example, the trace information has been sorted by category.
ASP.NET also provides a way to enable tracing for the entire application, not just a single page. For more about application-level tracing, click here. Section Summary
|