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.
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.
精彩评论