[EN] Using Logger with @Produces

Logging the events is crucial so how can we use Logging mechanism into our Jakarta EE projects? Here we go :

import java.util.logging.Logger;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;

/**
*
* @author altuga
*/
public class LogManager {

   @Produces
   public Logger configure(InjectionPoint point) {
     String name = point.getMember().getName();
     return Logger.getLogger(name);
   }
}

In order to use Logger in your project, just inject the Logger and start using it like this :

import java.util.List;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import org.eclipse.microprofile.metrics.annotation.Metered;


@Path("/ping")
@Stateless
public class PingResource {

   @Inject
   Pingy pingy;

   @Inject
   Logger logger;

   @GET
   public String ping() {
     return pingy.pingMe();
   }

   @POST
   @Metered
   public void save(Ping ping) {
    logger.info("save method called...");
    pingy.save(ping);
  }

   @GET
   @Path("/all")
   public List<Ping> getAll() {
     return pingy.getAll();
   }
}

After that, you should be able to see the logs in app server’s log management system.

Enjoy

No Comments

Post a Comment

Comment
Name
Email
Website