Cleaner logging with Log4j, Commons Logging and java.util.logging
Logging frameworks are the Java programmer’s finger exercise — think content management systems for PHP programmers.
Most libraries these days use either Log4j or commons-logging, which is fine because SLF4J can replace commons-logging and redirect output from classes using either API to Log4j.
Problems only arise when the odd library uses the java.util.logging log framework. Not only is it initialized globally, it also can’t be replaced on the classpath because of its location in java.*. And its output is ugly.
With the public interest in Log4j, commons-logging and java.util.logging something like 100 : 10 : 0.5 (source: AdWords), not even Sun using the JDK for leverage can turn a mediocre also-ran product into a winner.
This means that java.util.logging must go. Thankfully, there’s a SLF4JBridgeHandler in SLF4J, but how to replace java.util.logging loggers with the SLF4JBridgeHandler?
import java.util.logging.LogManager
import java.util.logging.Logger
import org.slf4j.bridge.SLF4JBridgeHandler
class KillJavaUtilLogging {
static {
Logger log = LogManager.logManager.getLogger('')
while (log.parent) {
log = log.parent
}
log.with {
handlers.each { removeHandler(it) }
addHandler(new SLF4JBridgeHandler())
}
}
}
Now, simply mentioning KillJavaUtilLogging will redirect all java.util.logging output into SLF4J where it is logged using Log4j (or commons-logging, if you want).
class BlobFilter implements Filter {
{
KillJavaUtilLogging
}
}
The corresponding Maven POM dependencies might look like this:
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jul-to-slf4j</artifactId> <version>1.6.2</version> </dependency>
