How to inject logger using Google Guice
guice, java, logging
Solution
Please check the Custom Injections on Guice wiki, there is a complete Log4J example.
EDIT: You can use either a `static` field or a `final` field for your logger, but not a `static final` one. This is a Java limitation.
Also be wary that:
Injecting final fields is not recommended because the injected value may not be visible to other threads.
Haven't tested that but the code in the article should work fine for static fields, although you could improve it by getting rid of MembersInjector and doing all of it in the TypeListener (since a static field needs to be set only once).
Using `requestStaticInjection()` will force you to list all your classes in a module file - not a good idea, as you will soon forget to add one.
OTOH if you just want to support JUL you might be better of using the built-in support (as mentioned by Jeff, I assumed you didn't want a general answer, since you didn't mention JUL specifically in your question).
Problem
Usually I define logger like this: ``` private static final Logger logger = LoggerFactory.getLogger(MyClass.class); ``` But when using `@Inject` we must use non-static and non-final field, like: ``` @Inject private Logger logger; ``` i.e. logger will be created in each instance of this class, also logger is mutable. May be exist some way to make logger static? Also how I can bind logger to certain class (I use send the class object when creating logger object from factory `LoggerFactory.getLogger(MyClass.class);`, how to create logger in same way using injecting ? )?