Markus
Markus

Reputation: 3627

Log4net: Logger instantiation

guys. I have a question regarding usage of loggers in log4net. When choosing between logger per class (static readonly field) and logger per instance (readonly field) what is a better approach? Personally, the only disadvantage I see when having logger per class is its instantiation:

log4net.LogManager.GetLogger(
        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType

It doesn't look very nice because of reflection. If I create logger in the following way:

log4net.LogManager.GetLogger(typeof(MyClass))

there are chances that accidentally I will make copy/paste errors and instead of typeof(MyClass) I can supply typeof(SomeOtherClass), which is bad.

When using logger per instance, I can use:

log4net.LogManager.GetLogger(this.GetType())

This approach doesn't use reflection and is free of copy/paste errors.

Are there any other thoughts on this?

Upvotes: 4

Views: 1842

Answers (1)

Roy Dictus
Roy Dictus

Reputation: 33149

Besides the fact that it would be better to use dependency injection, I think your approach is good. I have used this approach myself in the past.

Upvotes: 4

Related Questions