Over a million developers have joined DZone.

Inject SLF4J Logger by Annotation

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.


Actually, the following class is not written by me. It is written my colleage. I know he is referencing from another post from Java Geeks. I found this is quite handy so I put it here as a reference.

The main idea is make use of the BeanPostProcessors interface. We first create an "LoggableInjector" class which implement the BeanPostProcessors interface.
This injector class gets the SLF4J logger and assign to the beans property after the bean creation by the Spring IOC continaer.

1. Create Loggable annotation
@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.FIELD) 
@Documented 
public @interface Loggable {
 //for slf4j
}  

2. Create LoggableInjector class to add logger to the bean
@Component
public class LoggableInjector implements BeanPostProcessor {       
 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 
  return bean; 
 } 

 public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException { 
  ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { 
   public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { 
    // make the field accessible if defined private 
    ReflectionUtils.makeAccessible(field); 
    if (field.getAnnotation(Loggable.class) != null) {
     Logger log = LoggerFactory.getLogger(bean.getClass());     
     field.set(bean, log); 
    } 
   } 
  }); 
  return bean; 
 } 
} 

3. Usage Example

@Service
public class ReportServiceImpl {

 @Loggable
 private Logger logger;

}

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

Topics:
java

Published at DZone with permission of Boris Lam, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}