Google guice has a built-in logger binding. But what if I want to use a commons-logging or log4j logger?
Can I get guice to inject a Log created by
LogFactory.getLog(CLASS.class)
But having the same behavior as in built-in binding:
The binding automatically sets the logger's name to the name of the class into which the Logger is being injected..
Does it even makes sense? Or shout I simply use the built-in java Logger? Or just use commons-logging without injections?
The CustomInjections page on the Guice wiki describes exactly how to inject a logger named by the class it's being injected into.
It's your choice. I've successfully used
logback
with Guice using the method detailed on the wiki.Have a look at the sli4j project. It might be useful.
Although you can't override the provided
java.util.logging.Logger
logger, you bind a new logger just like you would any other class:But, creating a named logger is going to be a bit more difficult.
If you dig through the Google Guice code (util.BinderImpl.java:87) you can see how they assign a distinct class name for each instance of the logger that's injected. However, I haven't inspected it carefully enough to know if it's easily reproducible.
It might be possible to create a provider or inject a factory which somehow has access to the context so you can provide a named logger.
Guice is very useful for injecting different implementations of an interface. This isn't the case here as the different logging implementations out there all have different APIs.
If you want to be able to exchange the actual logging implementation later while developing against an interface use commons logging or slf4j.