Thursday, August 4, 2011

Get Caller Class

Assuming you were going with something like cfeduke's answer above, you could also add an overload to your LogManager like this:

public static ILog GetLogger() {     var stack = new StackTrace();     var frame = stack.GetFrame(1);     return new Log4NetWrapper(frame.GetMethod().DeclaringType); } 

That way in your code you can now just use:

private static readonly ILogger _logger = LogManager.GetLogger(); 

instead of either of these:

private static readonly ILogger _logger =     LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILogger _logger =      LogManager.GetLogger(typeof(YourTypeName)); 

Which is effectively equivalent of the first alternative (i.e. the one that usesMethodBase.GetCurrentMethod().DeclaringType), only a little simpler.

No comments: