Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4Net: How to get Logger?

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.

like image 815
David Veeneman Avatar asked Aug 19 '10 16:08

David Veeneman


1 Answers

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.

like image 100
Russ Avatar answered Nov 07 '22 07:11

Russ