Core Java

Allocation free logging with log4j2


Recently I was working for a client trying to remove some GC pauses for a large well crafted Java system. After profiling I realised that most of the garbage was being produced by logging!! Was there a simple unobtrusive way to remove all that allocation?  Turns out there was :)

Which framework should I use for GC free logging?

Let’s turn our attention back to the age old question of which logging framework to use.

The usual candidates are

  • log4j2
  • logback
  • java.util.logging
  • slf4j (simple)

and unless you are doing something super funky you might not think it makes a huge difference which one you choose.

There have been many studies done comparing performance and those of course this can be important if you are playing in the ultra low latency arena. (see Benchmarking Java logging frameworks)

But what I’m concerned about is allocation!!

See my earlier post on the evils of allocation The First Rule of Performance Optimisation.  

In a typical system 30%-50% of all allocation can be in logging!! So even if most people don’t mind if logging takes a couple of milliseconds longer in one framework than another they will almost certainly care about long GC pauses caused by the garbage created by the logging framework.

And all this logging allocation can be removed by simple configuration. Log4J2 from 2.6 onwards is allocation free so really no excuse not to take advantage of it :)

Let’s see it in action

It’s one thing making the allocation free claim but let’s see if this holds true in practice.

Consider this simple logging code below: Note that I’ve used slf4j in the code and therefore only need change the configuration to run with the different logging frameworks.  It’s a good idea to do this because although log4j2 might be the best framework at the moment who knows what tomorrow will bring…

package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class GCLogger {
    private final static Logger LOGGER = LoggerFactory.getLogger(GCLogger.class);
    public static void main(String[] args) throws InterruptedException {
        List<String> list = IntStream.range(0,(int)1e6)
                .mapToObj(i->"" + i)
        //Log 1 million lines in a loop sleeping 1 second between each iteration of the loop
        //to allow time to run Flight Recorder.
        for (int i = 0; i < 1000; i++) {
            list.forEach(s->"Logging [{}]", s));

Run with log4j2 – no allocation

If we configure the program to run with log4j2 using this maven configuration:


And we use this log4j2 configuration

xml version="1.0" encoding="UTF-8" ?><Configuration status="INFO">
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss:SSS} [%t] %-5level %logger[36] %msg%n"></PatternLayout>
        <File name="MyFile" fileName="all.log" immeadiateFlush="false" append="false">
            <PatternLayout pattern="%d{dd MMM yyyy HH:mm:ss,SSS} [%t] %-5level %logger[36] %msg%n"></PatternLayout>
        <Root level="debug">
            <AppenderRef ref="MyFile"></AppenderRef>

Then we get 0 allocation!

We can prove this by running Flight Recorder on the program (see below):

The only memory being allocated is due to Flight Recorder (by the way FR can be configured so that this doesn’t happen).

Run using logback

Try exactly the same this using Logback.

Use this Maven configuration


Use this logback configuration:

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
            <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <root level="debug">
        <appender-ref ref="FILE" />

And when we run with Flight Recorder we see a hug amount allocation!

But a word of warning….

You need to use the log4j2 configuration exactly as specified in the documentation see supported layouts.  If you even change date format slightly allocation will again be rampant.


  • Use slf4j so that you can easily change your logging implementation
  • Use log4j2 to avoid allocation
  • Make sure you use the supported formats to support allocation free logging
Published on Java Code Geeks with permission by Daniel Shaya, partner at our JCG program. See the original article here: Allocation free logging with log4j2

Opinions expressed by Java Code Geeks contributors are their own.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Daniel Shaya

Daniel has been programming in Java since it was in beta. Working predominantly in the finance industry he has created real time trading and margin risk applications. He is currently a director at OpenHFT where we are building next generation Java low latency products.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button