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

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

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

1 comment:

  1. I had to add a scope to the Producer class

    public class Resources {