mo.notono.us

Wednesday, January 17, 2007

ASP.NET, C#: Simpler Trace

I found myself needing to trace some variables in my ASP.NET app, but rather than calling Page.Trace from my pages, and HttpContext.Current.Trace from my static utility methods, I decided to simplify standardize the process. The result is below; it uses the Callstack and Reflection to determine the type and name of the member that called the trace method:

/// <summary>
/// Writes a name and value to the Trace output, categorized by the type and member 
/// (property or method) from which the method was called.
/// </summary>
/// <param name="name">Name of variable to trace.</param>
/// <param name="value">Value of variable to trace.</param>
public static void WriteTrace(string name, object value)
{
  System.Reflection.MethodBase callingMethodBase = new 
    System.Diagnostics.StackTrace().GetFrame(1).GetMethod();
  string callingMethod = string.Format("{0}.{1}", 
    callingMethodBase.DeclaringType.Name, 
    callingMethodBase.Name);
  string message = string.Format("{0}: {1}", name, value);

  HttpContext.Current.Trace.Write(callingMethod , message);
}

Labels: ,

0 Comments:

Post a Comment

<< Home