2012-01-12

Tip: Injected Logger using CDI

In the good old days we used

        private Logger log = Logger.getLogger( getClass().getName() );  

for creating a logger. This has to be done in all classes that do logging. With CDI we can make our life easier, we simply inject the Logger using

    @Inject   
    private Logger log;   

but we have to define the Producer for the Logger in a separate class that must be part of the same deployment unit.  This can be done using

  package com.prodyna.demo.key.util;   
     
  import java.util.logging.Logger;   
     
  import javax.enterprise.inject.Produces;   
  import javax.enterprise.inject.spi.InjectionPoint;   
     
  public class Resources {   
     
    @Produces   
    public Logger produceLog(InjectionPoint injectionPoint) {   
      return Logger.getLogger(injectionPoint.getMember().getDeclaringClass()   
          .getName());   
    }   
  }   

The effort is ok, because we have to define the Resource class only once and benefit from the shorter Logger definition in multiple places.