Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SLF4J, To avoid writing LoggerFactory.getLogger(MyClassName.class) every time

Tags:

java

slf4j

log4j

I am writing a web application in Java and using SLF4J for logging.

I'm becoming tired of writing the below line for every class that uses logging:

private static final Logger logger = LoggerFactory.getLogger(ThisClassName.class);

To avoid redundant codes, I am thinking something like

interface Loggable {
    Logger logger();
}

and each class can just implement this interface then some magic like AOP inserts the LoggerFactory part.

Has anyone implemented this or knows how to achieve this?

Thanks!

like image 242
lyomi Avatar asked Nov 30 '12 08:11

lyomi


2 Answers

Are you using eclipse? If so, why not just use a code template with a keyword like "logger" and the following template for it:

${:import(org.slf4j.LoggerFactory, org.slf4j.Logger)}
private static final Logger LOGGER = LoggerFactory.getLogger(${enclosing_type}.class);

This way you would just type "logger", hit shift+space and you are done.

like image 111
Hermann Hans Avatar answered Oct 03 '22 16:10

Hermann Hans


Are you using CDI? if so, create a producer method and then @Inject the logger to any CDI enabled class.

@Produces Logger createLogger(InjectionPoint injectionPoint) { 
    return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName()); 
}

See http://docs.jboss.org/weld/reference/latest/en-US/html/injection.html#d0e1662

like image 39
Ali Cheaito Avatar answered Oct 03 '22 17:10

Ali Cheaito