The easiest and quickest way to get around these limitations of Trace is to encapsulate all the functionality so that we can call it in one line. One way to do this is to create a class such as so.
using System;
namespace My
{
public class Trace
{
public static void Write(string Message)
{
if (System.Web.HttpContext.Current.Trace.IsEnabled)
{
try
{
System.Web.HttpContext.Current.Trace.Write(Message.ToString());
}
catch(Exception e)
{
System.Web.HttpContext.Current.Trace.Warn("Intranet.Web","Write",e);
}
}
}
public static void Write(string Category, string Message)
{
if (System.Web.HttpContext.Current.Trace.IsEnabled)
{
try
{
System.Web.HttpContext.Current.Trace.Write(Category.ToString(),Message.ToString());
}
catch(Exception e)
{
System.Web.HttpContext.Current.Trace.Warn("Intranet.Web","Write",e);
}
}
}
public static void Write(string Category, string Message, System.Exception exe)
{
if (System.Web.HttpContext.Current.Trace.IsEnabled)
{
try
{
System.Web.HttpContext.Current.Trace.Write(Category.ToString(),Message.ToString(),exe);
}
catch(Exception e)
{
System.Web.HttpContext.Current.Trace.Warn("Intranet.Web","Write",e);
}
}
}
public static void Warn(string Message)
{
if (System.Web.HttpContext.Current.Trace.IsEnabled)
{
try
{
System.Web.HttpContext.Current.Trace.Warn(Message.ToString());
}
catch(Exception e)
{
System.Web.HttpContext.Current.Trace.Warn("Intranet.Web","Write",e);
}
}
}
public static void Warn(string Category, string Message)
{
if (System.Web.HttpContext.Current.Trace.IsEnabled)
{
try
{
System.Web.HttpContext.Current.Trace.Warn(Category.ToString(),Message.ToString());
}
catch(Exception e)
{
System.Web.HttpContext.Current.Trace.Warn("Intranet.Web","Write",e);
}
}
}
public static void Warn(string Category, string Message, System.Exception exe)
{
if (System.Web.HttpContext.Current.Trace.IsEnabled)
{
try
{
System.Web.HttpContext.Current.Trace.Warn(Category.ToString(),Message.ToString(),exe);
}
catch(Exception e)
{
System.Web.HttpContext.Current.Trace.Warn("Intranet.Web","Write",e);
}
}
}
}
}
If you place the above in to a class file in your project, you can then use it as a 1 line replacement for Trace as so: -
private void Page_Load(object sender, System.EventArgs e)
{
if (Request.QueryString["Doesn'tExist"] != null)
{
My.Trace.Write(Request.QueryString["Doesn'tExist"].ToString());
}
}
This is all nice and neat and encapsulated now, and gives you a performance increase which scales with your application through debug and in to release, as well as error handling of your Trace commands, all this with the ease of use of the Trace methods them selves.