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
    public Logger produceLogger(InjectionPoint injectionPoint) {
		return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());

in classes:

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

Glassfish tips: default encoding


Glassfish-Tips: UTF-8 Encoding

Glassfish 3.1.2 has default encoding ISO-8859-1. If you get a warning like below in Eclipse console (Server.log):

WARNING: PWC4011: Unable to set request character encoding to UTF-8 from context, because request parameters have already been read, or ServletRequest.getReader() has already been called

you can add parameter-encoding  in the sun-web.xml, or glassfish-web.xml as shown below:

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE sun-web-app PUBLIC “-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN”
<sun-web-app error-url=”">

<parameter-encoding default-charset=”UTF-8″/>

Then your Glassfish server.log looks cleaner.