Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get google guice to inject a custom logger, say a commons-logging or log4j logger

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?

like image 571
Miguel Silva Avatar asked Apr 09 '10 05:04

Miguel Silva


People also ask

How does Guice @inject work?

Guice figures out how to give you an Emailer based on the type. If it's a simple object, it'll instantiate it and pass it in. If it has dependencies, it will resolve those dependencies, pass them into it's constructor, then pass the resulting object into your object.

What is @inject annotation in Guice?

Annotation Type Inject. @Target(value={METHOD,CONSTRUCTOR,FIELD}) @Retention(value=RUNTIME) @Documented public @interface Inject. Annotates members of your implementation class (constructors, methods and fields) into which the Injector should inject values.

What does bind mean in Guice?

Overview of bindings in Guice. A binding is an object that corresponds to an entry in the Guice map. You add new entries into the Guice map by creating bindings.

How do you inject a Guice class?

The implementation is very easy to understand. We need to create Injector object using Guice class createInjector() method where we pass our injector class implementation object. Then we use injector to initialize our consumer class. If we run above class, it will produce following output.


2 Answers

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

like image 131
Jesse Wilson Avatar answered Oct 17 '22 03:10

Jesse Wilson


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.

like image 23
gpampara Avatar answered Oct 17 '22 04:10

gpampara