I think the common idiom for creating instances of java.util.logging.Logger
is this:
public class SomeClassName {
private static final Logger LOG = Logger.getLogger(SomeClassName.class.getName());
}
My IDE will manage changing the line appropriately when I refactor my code (change the name of the class, for example). It still bugs me that I have to repeat the name of the class, though. What I'd really like to do is something like Logger.getLogger(getName())
or Logger.getLogger(class.getName())
, but this isn't legal Java in a static initilization.
Is there a better way of getting at a logger that doesn't involve repeating myself?
In Java, logging is an important feature that helps developers to trace out the errors. Java is the programming language that comes with the logging approach. It provides a Logging API that was introduced in Java 1.4 version. It provides the ability to capture the log file.
To use a different Layout with java. util. logging , set the Appender 's formatter property to the Layout of your choice. To do this in code, you can create a new Handler and use its setFormatter method, then assign the Handler to the Logger using logger.
Issue 137 of The Java Specialists' Newsletter deals with this problem. It recommends applying a logger factory, which can detect the actual class name e.g. by generating an exception and analysing the call stack.
I personally find this worse than the original problem, but this is just my 2 cents. At any rate, technically it is interesting, so here it is:
public class LoggerFactory {
public static Logger make() {
Throwable t = new Throwable();
StackTraceElement directCaller = t.getStackTrace()[1];
return Logger.getLogger(directCaller.getClassName());
}
}
...
public class BetterApplication {
private final static Logger logger = LoggerFactory.make();
...
}
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