简体   繁体   中英

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 AuthorizedController , and if I have FooController inherited from AuthorizedController I'd like the log output to reflect that.

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

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.

I did something similar by using NInject as an IoC container, but I suppose you can grab the idea to use with your own container. Basically I inject ILog on the requesting types constructor, but instead of binding to an instance, I bind it to a provider .

  kernel.Bind<ILog>().ToProvider<MyProvider>();

public object Create(IContext context)
{
    return LogManager.GetLogger(context.Request.Target.Member.DeclaringType);
}

so each type receive a logger that is the same as doing GetLogger(GetType()) in the constructor.

As Steve Guidi suggested - use GetType to create logger for specific instance of type. You can save reference to instance of logger which gets calling LogManager.GetLogger in backing field:

    private ILog _log;
    protected ILog Log => _log ?? (_log = LogManager.GetLogger(GetType()));

Having a static logger (or static instances in general) is a bad practice. It can easily lead to undesired coupling between unrelated components.

You should consider adding an dependency Injection/Inverse of Control framework to the game. Have the logger injected to the ctor of the class. Most frameworks allows you to define different implementations to in different contexts.

We use Castle Windsor in our products

You can also look at this post to find an example of using logging together with DI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM