Idioms for loggers in Java code:
An often used idiom for logger configuration in Java code uses log4j. Following is a code snippet that demonstrates the usage:
Import statement:
import org.apache.log4j.Logger;
Declaration and generation example within a class:
public class Foo {
private static final Logger logger = Logger.getLogger(Foo.class);
Usage example within that class:
if(logger.isDebugEnabled()) {
logger.debug("this will be logged with the following parameters x="+x+" y="+y+" z="+z);
}
A newer implementation provides an idiom that internally tests for the effective log level and thus builds up the string (with the required concatenations) only if the log message will actually eventually be streamed to the appender. As a result, the format of the method for logging changes to something that actually evaluates strings only if the suitable log level is used. For example, when logging is disabled at the DEBUG level, the logging framework does not need to evaluate the string representation of the values.
Import statement:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Declaration and generation example within a class:
public class Foo {
private static final Logger logger = LoggerFactory.getLogger(Foo.class);
Usage example within that class:
logger.debug("this will be logged with the following parameters x={} y={} z={}",new Object[] {x,y,z});
So, the slow and inefficient idiom
logger.debug("this will be logged with the following parameters x="+x+" y="+y+" z="+z);
which also took additional awkwardness with the attempt to reduce its performance costs by using this idiom
if(logger.isDebugEnabled()) {
logger.debug("this will be logged with the following parameters x="+x+" y="+y+" z="+z);
}
should now be replaced with the fast and more efficient
logger.debug("this will be logged with the following parameters x={} y={} z={}",new Object {x,y,z});
It is recommended to refactor log4j idioms to slf4j idioms when working on classes that use the inefficient idioms.
It is required to use te slf4j idiom in new implementations.
Some related links:
- Apache log4j
- slf4j
- LOG4J in wikipedia
- SLF4J in wikipedia
- Thoughts on Java logging and SLF4J by A Java Geek
No comments:
Post a Comment