I have a number of packages in my Java web application. In some of them I use this construct:
public class Foo {
private static Logger logger = LoggerFactory.getLogger("com.XXX");
public void bar() {
Foo.logger.debug("Method bar() was just called");
}
}
Of course, it’s just an example. Everything works fine, but I don’t like the idea of logger initialization in many classes. It’s an obvious code duplication. I would like to move it to some helper class and let all other classes access it. Is it a correct idea? Or maybe there is some other “best practice” or a pattern?
You could write your own utility class which wraps the global logger and implements static delegates to the logger methods. Then just do a static import of this class:
Usage:
Added an overloaded version of the example
debugdelegate which takes a class object and uses the appropriate Logger.