Dynamicaly Injecting Logger class

On the following way, it is possible to inject a logger class using CDI bean.


package com.ardevco

import org.apache.log4j.Logger;

public class LoggerProducer {
@Produces
public Logger produceLogger(InjectionPoint injectionPoint) {
return Logger.getLogger(injectionPoint.getMember.getDeclaringClass.getName());
}
}


Usage:

@Inject
private transient Logger logger;

Another way is injecting the Level as well:

@Produces

public Consumer<String> produceInfoLoggerInjectionPoint injectionPoint) {

String cls = ip.getMember().getDeclaringClass().getName();

return Logger.getLogger(cls)::info;

}

and the usage is:

@Inject
private Consumer<String> Logger logger;

public someMethod() {

LOG.log(“this is an info log”);

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s