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

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.


This may be an older post, but I'd like to chime in.

The idea that IOC of a logging system is overkill is short-sighted.

Logging is a mechanism by which an application developer can communicate with other systems (event logs, flat files, a database, etc.), and each of these things is now an external resource upon which your application is dependent.

How am I supposed to unit test my component's logging if my unit-tested code is now locked to a particular logger? Distributed systems often use loggers which log to centralize sources, not to flat files on the file system.

Injecting a logger, to me, is no different than injecting a database connection API or an external web service. It is a resource which the application requires, and as such, should be injected, so you can test the component's usage of said resourceThe ability to mock said dependence, to test the output of my component independent of the logging recipient, is crucial to strong unit testing.

And given that IOC containers make such injection child's play, it seems to me that NOT using IOC to inject the logger is no more valid an approach than doing so.


Now, in every class in which I want to do some logging I have extra constructor parameter

If you need logging many classes in your system, there is something wrong in your design. Either you log too much or you're violating the Single Responsibility Principle, since logging is a cross-cutting concern, and you should not clutter your classes with cross-cutting concerns like logging.

I answered a (totally different) question a half year back, and my answer is applicable to your question. Please read this.