Video in progress

What load does logging on a hot path (string concatenation, MDC, a synchronous appender) put on the JVM, and how do you reduce it?

Even with the log level off, the arguments may still be computed, MDC and formatting create objects on every request, and a synchronous appender ties the thread to disk or network I/O. Parameterized logs, an asynchronous appender for delivery, sensible levels and measurement cut the load noticeably.

📖 Answer

In one service, 18% of the flame graph was in Logback. Nobody had suspected it, because "logging is cheap".

The sources of cost:

log.debug("Order " + order + " items " + items);   // DEBUG is off, but toString() is still called
log.debug("Order {} items {}", order, items);       // formatted after the level is checked
log.debug("payload {}", () -> heavyDump(payload));   // Log4j2: a Supplier, computed only when needed
  • Formatting and toString. A big object's toString() (Lombok, entity collections) creates kilobytes of string. On a Hibernate entity it can even load a lazy collection.
  • A synchronous appender. FileAppender takes a lock while writing: 200 threads queue on one lock. In JFR, jdk.JavaMonitorEnter shows up in Logback classes. If the disk slows down, the whole service slows down.
  • Location information. %L, %M, %C in the pattern walk the stack on every entry, which is very expensive.
  • The JSON encoder and MDC. A copy of a many-field Map for every entry.

How to reduce it:

  • parameterized logs, and isDebugEnabled() or a Supplier for heavy arguments;
  • AsyncAppender (Logback) or Log4j2 async loggers; choose explicitly what happens when the buffer is full: wait or drop (neverBlock);
  • a pattern without location info on prod;
  • in a container, write to stdout and leave collection to an agent;
  • turn high-frequency events into metrics instead of logs: instead of "one INFO per request", a counter and a sampled log.

Log4j2's "garbage-free" mode brings allocation almost to zero, so it is worth considering for allocation-sensitive services. After every change, compare p99 and allocation rate under the same load.