Should logging infrastructure be injected when using IoC/DI if logging facade is used?

0

Issue

I am using Autofac as my IoC and from everything I have read on topic of DI teaches to use “constructor injection” to explicitly expose class dependencies…
However, I am also using logging facade (Common.Logging) with Log4Net and have created Autofac module to inject it.
Now, in every class in which I want to do some logging I have extra constructor parameter (see sample #1)….

I am wondering if logging DI is necessary when using logging facade?
I understand that explicitly exposing dependencies via constructor signature is a good architecture.
but in case of logging facade I believe following is true:

  • I can still “swap out” logging framework at any time
  • The class IMHO is not really dependent on Logger. If no logging is configured NullLogger is used. It is almost “it’s thre if you need it” vs. “it won’t work unless you supply it” kind of deal…(see sample #2)

So, what do others think? Is injecting logging facade an overkill?
There are some similar questions on this topic but in more general terms (infrastructure) – I am mainly interested in logging….

// IoC "way"
public class MyController : BaseController
{
    private readonly ILog _logger;

    public MyController(ILog logger)
    {
        _logger = logger;
    }

    public IList<Customers> Get()
    {
        _logger.Debug("I am injected via constructor using some IoC!");
    }
}

// just use the logger "way"
public class MyController : BaseController
{
    private static readonly ILog Logger = LogManager.GetCurrentClassLogger();

    public IList<Customers> Get()
    {
        Logger.Debug("Done! I can use it!");
    }
}

Solution

Logging is just infrastructure. Injecting it is overkill. I personally don’t even use an abstraction layer. I use the static classes that the library provides directly. My motivation is that it’s unlikely that I’ll switch logging library in a current project (but might switch for the next project).

However, you are using controllers in your example. Why do you need to log in them? A controller is just an adapter between the view and the model (business logic). There should be no need to log in it.

You typically do only log in classes which contains business logic and at the top layer to be able to log unhandled exceptions. Those are the hard cases to debug and therefore the places where logging is required.

Having to log at other places indicates that you need to refactor to encapsulate your business logic properly.

Answered By – jgauffin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More