Saturday, February 6, 2016

Upgrading to log4j2

 As you may already know log4j has reached end of life. But don't worry! log4j2 is here to the rescue and its way better. I've recently have been working on a migration from log4j1.xx to log4j2 in a maven managed Spring 4 app. Here are some of my findings.

Advantages of log4j2

There are lots of them but what I find the biggest reason for this upgrade is the asynchronous loggers & appenders. This offers a huge performance boost because now your application performance and your disk are now decoupled. (You could actually get async appenders working in log4j1, but now there is a performance boost)

The second thing that I thought was nice was allowing lambda expressions. This will lazily evaluate an expression only if it conforms to the log level threshold. This means that wrapping the code with isDebugEnabled() is unnecessary. Some orgs may feel it unnecessary now to use a logging abstraction like SLF4J

There's also other goodies like custom log levels and markers.

One very practical tip is Using log4j2 ThreadContext to enable per request debugging

Example log4j2 configuration


The above has a rolling file and syslog appender with async logging. Another way to turn on async logging for all appenders is to drop the LMAX Disruptor jar onto the classpath and set the Log4jContextSelector parameter to org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

In addition it shows how to setup a syslog appender. We use this to centralize logs in rsyslog and provide the logs to Logstash.

Here's hoping you make the transition to log4j2, theres a lot of improved features to look forward to.