CDI: static loggers vs injection?

Viewed 343

Disclaimer: this question is not intended to be "opinion based". I am looking for strong pros & cons.

In the CDI application what is more conventional and proper to use: a static logger: private static final Logger LOGGER = LoggerFactory.getLogger...;

or inject it having a specific producer? @Inject private Logger logger;

As an advantage of the former one is that we can create our own LoggerFactory wrapper (for some purposes) and use it all places without being care that somebody has misused another factory. But are any other disadvantages/advantages or this approach? What is more "canonical"?

1 Answers

Since all CDI Beans are light-weight proxies, there is no real disadvantage. The comment about a logger being a singleton is not completely accurate, depending on how you implemented it. The following will inject the correct logger instance based on the target:

    @Produces
    @Dependent
    public Logger createLogger(final InjectionPoint injectionPoint) {
        Class<?> declaringClass = injectionPoint.getMember().getDeclaringClass();
        return LoggerFactory.getLogger(declaringClass);
    }

The advantage really comes down to testing... you can now mock the injection and test just your actual business code. Static functions are generally very hard to mock and this provides a very clean way of not needing to deal with them.

Related