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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With