views:

302

answers:

4

Google guice has a built-in logger binding (http://code.google.com/p/google-guice/wiki/BuiltInBindings). 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?

+1  A: 

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.

gpampara
A: 

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.

Robert Petermeier
Hibernate uses SLF4J and I integrated both into a Guice based application without any problems, so I can recommend it, although I haven't played with commons logging.
Kaleb Pederson
A: 

Although you can't override the provided java.util.logging.Logger logger, you bind a new logger just like you would any other class:

bind(Log.class).to(LogFactory.getLog(YourClass)); // or toInstance(...);

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.

Kaleb Pederson
+3  A: 

The CustomInjections page on the Guice wiki describes exactly how to inject a logger named by the class it's being injected into.

Jesse Wilson
Nice link. Kind of a painful process, but functional nonetheless.
Kaleb Pederson
Thanks for the link. It worked for me. I used this strategy to implement a SLF4J solution.
Miguel Silva