Writing Trace Output


The information provided by ASP.NET when trace is enabled can go a long way toward increasing your understanding of both the page makeup and where the execution and view state costs are. Beyond that, for debugging code, trace provides a replacement for sprinkling Response.Write methods throughout your code. Using trace eliminates the need to scour your code to eliminate any lingering debug statements before your code goes into production.

The Trace object is actually of type TraceContext and is available by accessing the Trace property of page. It has two methods for writing trace information: Warn and Write. Both of these methods have three overrides. The first just takes a string that is the debug data you are recording. The second override adds a category string as the first parameter. When using the SortByCategory traceMode, the custom category can be very helpful in grouping similar types of output. The third override adds an exception parameter at the end. The exception data is then recorded as part of the trace information.

Tip

Implement an Application_OnError handler that traces error information so that if you encounter unusual behavior in an application, you are prepared to gather more information by simply enabling trace.

The difference between messages logged using Write and those recorded with Warn is the formatting of the output. Warn messages are highlighted as providing higher priority information. In Code Listing 10-4, we write messages using both Warn and Write, including an exception.

Code Listing 10-4: TraceWriteAndWarn.aspx

start example
 <%@ Page Trace="true" language="c#" %>
<script runat="server">
protected void Page_Load(object o, EventArgs e) {
Trace.Write("info", "some data goes here");
try {
throw new Exception("something exceptional has occurred");
}
catch (Exception exception) {
Trace.Warn("problem", "warn message", exception);
}
}
</script>
<asp:label runat="Server" Text="Hello" />
end example

When the page represented by Code Listing 10-4 executes, information about the exception, including where it was thrown, is included in the trace output. The text in the center of Figure 10-4 (“warn message”) is the result of calling the Warn method.

click to expand
Figure 10-4: Trace Warn output

The Trace facilities offer an easy way to quickly get good information about the control structure, view state usage, and execution properties of a page. As mentioned earlier, when you need help isolating a problem in your program, Trace is the perfect replacement for inserting simple debug info directly into the page code.




Microsoft ASP. NET Coding Strategies with the Microsoft ASP. NET Team
Microsoft ASP.NET Coding Strategies with the Microsoft ASP.NET Team (Pro-Developer)
ISBN: 073561900X
EAN: 2147483647
Year: 2005
Pages: 144

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