Get CurrentMethod information from a shared logging class to use with log4netJune 28, 2007 9:23One 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
Tags: .NET, log4net, logging, reflection, StackTrace.
{ 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) public static void Info(string message) |
||