Get CurrentMethod information from a shared logging class to use with log4net

June 28, 2007   9:23


One of the most common ways to create a log object for log4net is to declare it in every class file like

log4net.ILog log = log4net.LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType );

It would be much nicer if we could use a shared class to log. With a shared class we can always change the logging engine with a different one like the Health Monitoring in ASP.NET 2.0. The problem is that we cannot use the GetCurrentMethod function to track the name of the class and function that we are logging.

To solve this issue we can make use of the StackTrace. The sample below shows you how to create a shared logging class that resolves the name of the class and function that writes to the log.

public static class Log
{
 private static string GetClassInformation()
 {
  StackTrace callStack = new StackTrace(); // Get the call Stack
  StackFrame frame = callStack.GetFrame(2); // Go 2 steps back
  MethodBase method = frame.GetMethod(); // Get the method
  return string.Format(”{0}.{1}”, method.DeclaringType.Name, method.Name);
 }

 public static void Debug(string message)
 {
  log4net.ILog log = log4net.LogManager.GetLogger(GetClassInformation());
  log.Debug(message);
 }

 public static void Info(string message)
 {
  log4net.ILog log = log4net.LogManager.GetLogger(GetClassInformation());
  log.Info(message);
 }
}

Tags: , , , , .









The content expressed in this blog are those of Edwin Vriethoff and do not represent his employer's view in anyway. The contents of this blog has been carefully put together, but Edwin Vriethoff is not responsible in any way for any direct or indirect harm caused by individuals or organizations using the content of this blog in any way.