Sep 17 2012
Injectable Logger with CDI
In my Java EE projects I don’t like logger configuration in every classes such as below:
private Logger logger = Logger.getLogger(this.getClass().getName());
I want to use with @Inject annotation. Fortunately there is @Produces annotation for it (see CDI – JSR 299: Context and Dependency Injection). I’m writing a producer class then I can @Inject logger everywhere as below:
package com.devsniper.demoapp.util; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; import org.apache.log4j.Logger; /** * Logging producer for injectable log4j logger * * @author cem ikta */ public class LoggerProducer { /** * @param injectionPoint * @return logger */ @Produces public Logger produceLogger(InjectionPoint injectionPoint) { return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName()); } }
in classes:
@Inject private transient Logger logger;
I am using log4j in producer class but this works well for java logger too. Transient keyword is important, without transient keyword you get the following error in GlassFish:
WELD-000054 Producers cannot produce non-serializable instances for injection into non-transient fields of passivating beans\\n\\nProducer\: Producer Method [Logger] with qualifiers [@Any @Default] declared as [[method] @Produces public com.devsniper.demoapp.util.LoggerProducer.produceLogger(InjectionPoint)]\\nInjection Point\: [field] @Inject private com.desniper.demoapp.controller.UserController.logger