Ditching JCL for SLF4J

When discussing these two logging API's it really comes down to dynamic discovery vs. statically bound bridging mechanisms. As Ceki Gülcü wrote in his 2009 article detailing the problems with JCL:

Class loading problems encountered when using JCL fall into three main categories:
  • Type-I: A java.lang.NoClassDefFoundError thrown when a class is inaccessible from a parent class loader even if the said class is available to a child class loader
  • Type-II: Assignment incompatibility of two classes loaded by distinct class loaders, even in case where the two classes are bit-wise identical.
  • Type-III: Holding references to a given class loader will prevent the resources loaded by that class loader from being garbage collected.
The article goes on to provide highly detailed descriptions of the problem while including code samples demonstrating the bugs in action.

Well, it turns out that on seeing these problems with the JCL, the good people on the log4j project decided to go another direction and create the Simple Logging Facade for Java (SLF4J) project. From the SLF4J site:

The Simple Logging Facade for Java or (SLF4J) serves as a simple facade or abstraction for various logging frameworks, e.g. java.util.logging, log4j and logback, allowing the end user to plug in the desired logging framework at deployment time.

What does it do?

SLF4J provides logging related interface to code against. By doing so, the resultant code is implementation agnostic and has only a single build-time dependency (the SLF4J library). Implementations are specified by runtime classpath configuration. The inclusion of a single library either bridging to a specific logging framework (log4j, JUL, or even JCL) or a direct implementation such as Logback will trigger the use of that implementation by SLF4J's static binding mechanism. Finally, this API provides parameterized logging which improve performance.

How does this work?

Well, I'm summarizing here but, the core of the static binding code works by discovering implementations of org.slf4j.impl.StaticLoggerBinder on the application classpath. This magic is done in the LoggerFactory. Specifically at:

private final static void bind() {
  try {
    // the next line does the binding
    StaticLoggerBinder.getSingleton();
    ...

StaticLoggerBinder classes provided by SLF4J bridges or implementations tie the API to the concrete frameworks. Here's an example in Logback.

Just Use It

Coding against SLF4J will make your life a bit easier. Bridges erode excuses based on inheriting logging frameworks from your dependencies. Projects can freely float between logging implementations as capability and configuration requirements change. To quote Ceki Gülcü, "In summary, statically bound discovery provides better functionality, with none of the painful bugs associated with JCL's dynamic discovery."