Structured Logging and Correlation IDs in Spring Boot: JSON Lines, a Filter and the MDC
Two requests run at the same moment and their eight log lines come out mixed. One property turns each line into JSON, and a small filter puts a correlation id in the MDC, ced7ac95 for one request and support-4711 for the other. Now a single query finds the four lines of one request.
What you will learn
- Switch Spring Boot's console log to JSON with one property
- Give every request a correlation id in a OncePerRequestFilter, or reuse the caller's
- Put the id in the MDC so every log line of that request carries it, and clear it afterwards
- Find all lines of one request among mixed lines from requests running at the same time
Before you start
- A Spring Boot REST API
- The Security Filter Chain and Your Own Rules
A customer writes in: "my ticket page was slow at 06:49." You open the logs and find a stretch of lines like "Loading ticket from the database" and "Ticket loaded". Several requests were running at that moment, and the lines don't say which request they belong to. This article fixes that in two steps: log lines become JSON with named fields, and every line of a request carries the same id.
Lines with no owner
The demo is a ticket desk with one endpoint, GET /tickets/{id}. The controller logs "Ticket requested", the service logs "Loading ticket from the database", waits 200 ms (a stand-in for a slow database), and logs "Ticket loaded". Two requests sent at the same time produce interleaved lines like these, with the default format:
... [io-54974-exec-1] org.studyeasy.s05l02.TicketController : Ticket requested
... [io-54974-exec-3] org.studyeasy.s05l02.TicketController : Ticket requested
... [io-54974-exec-1] org.studyeasy.s05l02.TicketService : Loading ticket from the database
The thread name helps a little, but threads are reused for the next request, and once the work moves to another thread or another service, it's no help at all.
Step 1: one property for JSON
spring.application.name=ticket-desk
logging.structured.format.console=ecs
Spring Boot has structured logging built in. ecs is the Elastic Common Schema format (logstash and gelf are also built in). spring.application.name ends up as service.name in every line. One real line, laid out over several lines here:
{
"@timestamp": "2026-11-10T06:49:05.342034200Z",
"log": { "level": "INFO", "logger": "org.studyeasy.s05l02.TicketService" },
"process": { "pid": 95868, "thread": { "name": "http-nio-54964-exec-1" } },
"service": { "name": "ticket-desk", "version": "0.0.1-SNAPSHOT", "node": {} },
"message": "Ticket loaded",
"correlationId": "ced7ac95",
"ecs": { "version": "8.11" }
}
Every value now has a name. A log store such as Elasticsearch, Loki or CloudWatch can filter on log.level or service.name without guessing where a column starts. And there's that correlationId field. It isn't part of the format: it comes from the filter below.
Step 2: one id per request
@Component
public class CorrelationIdFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(CorrelationIdFilter.class);
static final String HEADER = "X-Correlation-Id";
static final String KEY = "correlationId";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String id = request.getHeader(HEADER);
if (id == null || id.isBlank()) {
id = UUID.randomUUID().toString().substring(0, 8);
}
MDC.put(KEY, id);
response.setHeader(HEADER, id);
try {
chain.doFilter(request, response);
} finally {
log.info("Answered with status {}", response.getStatus());
MDC.remove(KEY);
}
}
}
A OncePerRequestFilter runs once for each request, before any controller. It reads the caller's X-Correlation-Id header. If there isn't one, it makes a short id from a UUID. Then three things happen:
MDC.putstores the id in the MDC (Mapped Diagnostic Context), a small map that belongs to the current thread. Every log line written on this thread now includes it, with no change to the logging calls.response.setHeadersends the id back, so the caller (or a support person) can quote it.- In
finally, the filter logs the status and callsMDC.remove. Request threads are reused; without the remove, the next request on this thread would carry the old id.
The service code didn't change. It still logs plain text, log.info("Ticket loaded"), and the id appears anyway.
Two requests at once
Request A came with no header, so the filter made ced7ac95. Request B sent X-Correlation-Id: support-4711, the kind of id a support tool or another service would pass along. Both answered 200, and each response carried its own id back in the header. The eight lines in order:
| Thread | Message | correlationId |
|---|---|---|
| exec-1 | Ticket requested | ced7ac95 |
| exec-6 | Ticket requested | support-4711 |
| exec-1 | Loading ticket from the database | ced7ac95 |
| exec-6 | Loading ticket from the database | support-4711 |
| exec-1 | Ticket loaded | ced7ac95 |
| exec-6 | Ticket loaded | support-4711 |
| exec-6 | Answered with status 200 | support-4711 |
| exec-1 | Answered with status 200 | ced7ac95 |
The lines still alternate, because the two requests really did run side by side; the 200 ms wait overlapped. But now a query for correlationId: support-4711 returns exactly four lines, the whole story of request B, and ced7ac95 returns the other four. "My ticket page was slow" turns into one query, if the customer can tell you the id from the response.
Where the MDC stops
The MDC belongs to one thread. Work handed to an @Async method, an executor or a Kafka message starts on another thread with an empty MDC, unless you copy the id over. Between services, the id has to travel in a header. That's the job of distributed tracing, which does the same for trace ids automatically and is the next step after this.
Common mistakes
- No
MDC.removeinfinally. The next request on the same thread logs with the previous request's id. - Not echoing the header. The id exists only in your logs, and nobody outside can quote it.
- Gluing the id into every message string by hand. It's easy to forget one, and the store can't filter a field that is part of the message text.
- Trusting any header value. It comes from the caller. Keep it short and simple, or make your own and log theirs next to it.
Try it yourself
Add a log.info("Request arrived") at the very top of the filter, before MDC.put, and delete the MDC.remove(KEY) line. Send one request with X-Correlation-Id: support-4711, then several without a header. Which id does "Request arrived" show when Tomcat reuses a thread, and why do the other lines still look right?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.
A Plain Spring Project, No Boot: Your First Bean With spring-context
One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.
Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.
Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.
