Remember way back to the top of the article, where I showed you an excerpt from the .NET SDK Documentation, it said “Trace statements are processed and displayed only when tracing is enabled.”?
It Lies. J
We can prove this by setting the Trace property on a page to False and then calling a trace command that will cause an exception, for example referencing an object that doesn’t exist such as a Querystring value: -
private void Page_Load(object sender, System.EventArgs e)
{
Trace.Write(Request.QueryString["Doesn'tExist"].ToString());
}
Calling this when Trace is enabled causes an exception to occur: -
Server Error in '/intranet' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 21: { Line 22: //Some fake business logic Line 23: Trace.Write(Request.QueryString["Doesn'tExist"].ToString()); Line 24: } Line 25: |
Source File: c:\inetpub\wwwroot\intranet\default.aspx.cs Line: 23
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.] intranet._default.Page_Load(Object sender, EventArgs e) in c:\inetpub\wwwroot\intranet\default.aspx.cs:23 System.Web.UI.Control.OnLoad(EventArgs e) +67 System.Web.UI.Control.LoadRecursive() +29 System.Web.UI.Page.ProcessRequestMain() +718 |
Version Information: Microsoft .NET Framework Version:1.0.3705.288; ASP.NET Version:1.0.3705.288
This means that the statement “Trace statements are processed and displayed only when tracing is enabled.” is obviously a blatant lie.
This is also important in terms of costly operations, lets say you’ve put a large loop in to your page and it’s outputting data to the Trace log so you can debug it – why do we need to call this when Trace is turned off?
A solution is provided in the form of Trace.IsEnabled(), we can check to see if Tracing is enabled before we run the Trace commands, like this: -
private void Page_Load(object sender, System.EventArgs e)
{
if (Trace.IsEnabled)
{
Trace.Write(Request.QueryString["Doesn'tExist"].ToString());
}
}
Now, that means we now have to write four lines of code for every Trace we have to write, which is really not an inviting thought – Trace is supposed to make things EASIER not HARDER!
Let’s also add some error handling to our Trace command to make sure that even when we get errors we can handle them properly: -
private void Page_Load(object sender, System.EventArgs e)
{
if (Trace.IsEnabled)
{
try
{
Trace.Write(Request.QueryString["Doesn'tExist"].ToString());
}
catch (Exception ex)
{
Trace.Warn("Trace","Exception",ex);
}
}
}
Now, our simple 1 line Trace.Write call is 11 lines long! Messy I hope you’ll agree.