In a previous post I described how you can log from your java applications to Logentries using log4j and logback with our open source le_java repository on github. Well now thanks to github user joshuadavis you can now log from log4j2 too!

See our product documentation on how to get started with le_java and log4j2, and here is the apache documentation for log4j2.

Using log4j2 has some benefits over log4j, and is quite easy to transition to from log4j using the log4j 1.x bridge, which simply involves changing your log4j dependency to log4j2’s log4j-1.2-api.jar. There are some limitations on this method which are described in full here on the log4j2 migration documentation.

You can also change over to log4j2 API entirely, although the above can be a good stop-gap while you update your logging code.

Why use log4j2?

One of the most obvious changes in log4j2 is that it now supports message objects, which allows for direct logging of java objects with the ability to write custom layouts, filters and lookups for them. This is in contrast to typical logging of a toString() method or grabbing individual fields as strings and concatenating them together with some user defined context. The log4j2 message objects set this up once and are subsequently reused, clarifying code for readability and DRYing it up. In general it is better to include as much contextual information as possible in a log event for future analysis, and putting all that formatting and contextual strings into your log methods every time can get ugly and difficult to read.

Something to bear in mind is that logentries supports named capture groups in our regex queries, so even unstructured data can be evaluated as a key value pair, aggregated and used in our dashboards and graphs. This means that you don’t need to worry as much about the format of the data you are logging, just that it is there with some identifiable context. Using a message object to define this in log4j2 seems like a nice way to do this, and allows you to put more information into your log while keeping your code readable.

Log4j2 also removes some of the concurrency issues that were present in log4j and logback, including deadlock issues and provides some substantially increased throughput and reduced latency. Logging should be a cheap, asynchronous action in an application and done as frequently as desired. The plugin system is also very extensible, our own appender is added as a plugin for example, and this pattern allows for flexible addition of other third party appenders and extensions in future, you might not need to migrate to another logging library again.

Some sample configs

Our own sample configuration file for log4j2 is here.

Thanks to github user apiraino for this config which demonstrates writing to file, rolling file, console and Logentries.