Logger CDI Injection

In this post I will show you how to inject an instance of Logger class using CDI (Context Dependency Injection) and SLF4J (Simple Logging Facade for Java).

To keep it simple, we only have a xhtml page (index), a managed bean (Controller.java) and the producer (LoggerProducer.java). The project configuration is as follows:

project
project

 

As we are using JSF with facelets, the index page looks like:

In this file we simply display the name that is setted in the controller (line 10).

 

In the controller we inject (@Inject) an instance of the Logger class and print to the console the name before and after the name is setted (lines 23 and 25). CDI knows which Logger to inject because we have a class that works as a factory of Loggers (LoggerProducer) with some special annotations.

 

In the LoggerProducer class we have an annotation (@Produces) in a method that returns a Logger instance. This is enough to CDI inject a Logger when needed. Notice that in line 13 we pass as a parameter the injection point (ip) in order to get the class where the logger is being injected (in this specific case ‘Controller.class’). This is only necessary beacuse the getLogger method needs it.

Finally, here are the results (the log and the web page):

log

log

As you can see here, we have two lines displaying the information that we expected: first the name is null and after the set of the variable name, name = John Doe.

the result page
the result page

 

That’s it. It’s just that simple!

Conclusion

First we create a factory of loggers, then we inject them whenever we need them:
@Produces to indicate CDI what we are producing and
@Inject to inject the instance ready to use.

Notice that this methodology works with other types rather than Logger. You may inject whatever you want by simply following the above technic.

Feel free to comment.

Source code