Log4j over SLF4J

Recent versions of SLF4J ship with a module called log4j-over-slf4j. It allows log4j users to migrate existing applications to SLF4J without changing a single line of code but simply by replacing the log4j.jar file with log4j-over-slf4j.jar, as described below.

How does it work?

The log4j-over-slf4j module contains replacements of most widely used log4j classes, namely org.apache.log4j.Category, org.apache.log4j.Logger, org.apache.log4j.Priority, org.apache.log4j.Level, org.apache.log4j.MDC, and org.apache.log4j.BasicConfigurator. These replacement classes redirect all work to their corresponding SLF4J classes.

To use log4j-over-slf4j in your own application, the first step is to locate and then to replace log4j.jar with log4j-over-slf4j.jar. Note that you still need an SLF4J binding and its dependencies for log4j-over-slf4j to work properly.

In most situtations, replacing a jar file is all it takes in order to migrate from log4j to SLF4J.

Note that as a result of this migration, log4j configuration files will no longer be picked up. If you need to migrate your log4j.properties file to logback, the log4j translator might be of help. For configuring logback, please refer to its manual.

We are happy to report that several applications are successfully using log4j-over-slf4j in production.

When does it not work?

The log4j-over-slf4j module will not work when the application calls log4j components that are not present in the bridge. For example, direct references to log4j appenders, filters or PropertyConfigurator are not supported by log4j-over-slf4j. While the number of cases where log4j-over-slf4j is insufficient is not completely negligible, in the vast majority of cases where log4j is configured through a configuration file, be it log4j.properties or log4j.xml, log4j-over-slf4j is enough in order to migrate your application to SLF4J.

What about the overhead?

There overhead of using log4j-over-slf4j instead of log4j directly is relatively small. Given that log4j-over-slf4j immediately delegates all work to SLF4J, the CPU overhead should be negligible, in the order of a few nanoseconds. There is a memory overhead corresponding to an entry in a hashmap per logger, which should be usually acceptable even for very large applications consisting of several thousand loggers. Moreover, if you choose logback as your underlying logging system, and given that logback is both much faster and more memory-efficient than log4j, the gains made by using logback should compensate for the overhead of using log4j-over-slf4j instead of log4j directly.