Jeremy Holovacs Jeremy Holovacs - 1 year ago 165
C# Question

log4net logger defined in base class

I want to build my log4net logger in my MVC controller abstract base class like so:

protected static readonly ILog Log = LogManager.GetLogger(typeof(AuthorizedController));

In this manner I can define the logger once and be done with it. The only problem is that the logger attribute in the log output will always be
, and if I have
inherited from
I'd like the log output to reflect that.

What would be a good KISS, DRY, and efficient way do doing this?

Answer Source

I'm not sure how expensive the call to LogManager.GetLogger() is, but I suspect that there is some clever caching and/or lazy initialization in the log4net system that keeps requested instances available for quick retrieval. After all, there is no reason why calling LogManager.GetLogger() twice with the same type parameter would return a different instance.

That said, perhaps replacing the field with the following property will suffice.

protected ILog Logger
    get { return LogManager.GetLogger(GetType()); }

GetType() is virtual and overloaded so each concrete type will supply its type when this property is called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download