10 Jan 5
The logging tool come with the java.util.logging package is just so horrible to work with, and most people tend to use Log4J, while open source project tend to use common-logging. And here, i would like to introduce a better (IMHO) logging tool — SLF4J. SLF4J is a facade wrapper, while you could choose your own implementation to be run below, and that includes Log4J, Java.util.logging, SimpleLogger and Logback. I personally would recommend the use of Logback as the logging implementation as it’s a better successor of Log4J. So, to use SLF4J, setup the project as follows:
1. Put into your lib folder the following jars:
slf4j-api.jar
logback-core.jar
logback-classic.jar
2. Then create a logback.xml or logback-test.xml in your classpath with the following content:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="STDOUT">
<layout>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{80} - %msg%n</pattern>
</layout>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
3. In your class, make use the logger as simple as follows:
// Simply get a logger from factory and start logging
Logger logger = LoggerFactory.getLogger("LogTest");
logger.debug("DEBUG MSG");
There’s one thing i like SLF4J so much is that, it actually supports parameterized logging:
// Parameterized logging reduce the hassle when constructing long log msg
Logger logger = LoggerFactory.getLogger("LogTest");
logger.debug("Error: {}, Reason: {}", error, reason);
And one more tips, sometimes when you want to override the original logging tool used in certain open source framework or codebase (e.g Spring Framework), you could simply add the jcl-over-slf4j.jar to the lib/, this will automatically hook into the common-logging of spring and replace it with SLF4J.
Hope this is useful! Enjoy!