DEV Community

Cover image for Log Log Log .. how to deforest with Java CDI
Ali Zaidi
Ali Zaidi

Posted on

Log Log Log .. how to deforest with Java CDI

Hello World!

..sorry had to do it. Welcome to my first dev.to post, hopefully the first of many!

I wanted to start off with a really simple utility that Java developers can easily integrate in their code and improve the codebase.

Something I see very often, usually in legacy projects, is a logger being declared for every class.

1   public class MyClass {
2 
3       private static Logger logger = LoggerFactory.getLogger(MyClass.class);
4
5   ...
6   }
Enter fullscreen mode Exit fullscreen mode

Realistically this won't be very resource intensive but we can definitely make improvements to simplify.

matrix

You don't know what it is, but it's there, like a splinter in your mind, driving you mad

Introducing.. logging with CDI!

With CDI, we can inject a SL4J (or your favourite implementation) logger.

First thing we need to do is implement a logging producer using the Injection Point API.

1   @ApplicationScoped
2   public class LoggerProducer {
3
4      @Produces
5      public Logger getLogger(final InjectionPoint ip) {
6          return LoggerFactory.getLogger(ip.getMember().getDeclaringClass());
6      }
7   }
Enter fullscreen mode Exit fullscreen mode

We specify the scope of the class as @ApplicationScoped. The injection point API allows us to know the declaring class of the injected logger.

Imports :

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Enter fullscreen mode Exit fullscreen mode

Note : Ensure that the correct @Produces annotation is imported, not the JAX-RS producer

Next step is to simply @Inject our logger into our class and begin to log.

1   @ApplicationScoped
2   public class MyClass {
3 
4       @Inject
5       private Logger logger;
6       
7       public void myMethod(){
8          logger.info("My log!");
9       }
10   }
Enter fullscreen mode Exit fullscreen mode

There we have it, an easy CDI logger.

There are other implementations such as a Lombok logger. However, there are some steps to make Lombok compatible with your IDE and I believe a CDI logger is easier to integrate with an existing codebase.

Top comments (0)