views:

39

answers:

1

I have been using Log4Net for several months, and I create a new Logger as a member variable for each class, like this:

// Member variables
private readonly ILog m_Logger = LogManager.GetLogger("MyClass");

Then I invoke the logger from each method in the class that logs, like this:

// Initialize
m_Logger.Info("MyClass.MyMethod() invoked.");
...
m_Logger.Debug("MyClass.MyMethod() did something...");
...
m_Logger.Info("MyClass.MyMethod() completed.");

Is there any reason not to use this approach, or is there a better way to set up the logger? Thanks for your help.

+2  A: 

Your logger should probably be static, and you can take advantage of other overrides, such as using the type:

private static readonly ILog m_Logger = LogManager.GetLogger(typeof(MyClass));

For improved performance, you should also check the log level you are in before calling the appropriate log function. For example:

if (m_Logger.IsDebugEnabled) { m_Logger.DebugFormat("Starting {0}", MethodBase.GetCurrentMethod().ToString()); }

The above example also shows using reflection to get the method name.

Russ
'using reflection to get the method name' - but you don't need to ask reflection to do a stack walk and consult the assembly metadata for the method name: you just typed it into the source file
Tim Robinson
It's just an example. Using reflection allows for simple cut-and-paste of the line to a multitude of places without having to edit the line for the correct method name.
Russ
Thanks! Accepted and +1
David Veeneman