Structured logging and traceId correlation in Spring Boot
Compare ECS, Logstash, and GELF formats in Spring Boot 4 and attach MDC traceId and spanId to JSON logs for Loki and Grafana trace correlation.
Converting plain single-line console logs into structured JSON and attaching
traceIdandspanIdlets you pull every log line for a single failing request in one query.
Environment: Spring Boot 4.0.1, Kotlin 2.2, Java 21, Micrometer Tracing (OpenTelemetry bridge), homelab OpenTelemetry Collector (
otel.namju.kim), Loki 3.6, and Grafana.
Background
During production incident response, root-cause analysis is rarely the slowest step. Gathering the right logs is. When a single user request fans out across an API server, internal HTTP calls, and background tasks, plain-text logs interleave in timestamp order. You end up cross-referencing timestamps and user IDs by eye just to reconstruct what happened.
At work, we already correlate traces and logs through OpenTelemetry, but the setup is split across shared internal libraries maintained by different teams. Because the wiring was spread out, I couldn’t see the whole picture at once. I decided to rebuild the entire pipeline from scratch in my homelab, starting with the first building block: emitting structured JSON logs with a trace ID on every line. I had previously set up centralized container logging with Docker and the ELK stack, but back then I had no way to tie an individual log line back to the exact request that produced it.
flowchart TD
A["Incoming HTTP request"] --> B["Micrometer Tracing\ncreates span"]
B --> C["Inject traceId & spanId\ninto MDC"]
C --> D["Emit structured\nJSON log"]
D --> E["Collect via OTLP\nor stdout"]
E --> F["Store in Loki &\nquery in Grafana"]
Project setup
Starting with Spring Boot 4.0, the Spring team ships a first-party spring-boot-starter-opentelemetry dependency. It bundles the OpenTelemetry API, micrometer-tracing-bridge-otel, and micrometer-registry-otlp together. As soon as tracing is active, Spring automatically populates traceId and spanId in SLF4J’s MDC for every tracked request.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// build.gradle.kts
plugins {
kotlin("jvm") version "2.2.21"
kotlin("plugin.spring") version "2.2.21"
id("org.springframework.boot") version "4.0.1"
id("io.spring.dependency-management") version "1.1.7"
}
java {
toolchain { languageVersion = JavaLanguageVersion.of(21) }
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-webmvc")
implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation("org.springframework.boot:spring-boot-starter-opentelemetry")
// Only needed when exporting logs over OTLP (Spring Boot does not auto-install the appender)
implementation("io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0:2.23.0-alpha")
implementation("org.jetbrains.kotlin:kotlin-reflect")
}
Built-in structured logging landed in Spring Boot 3.4 and requires no extra libraries—you enable it with a single property. In practice, I keep a human-readable pattern for local console output and switch to JSON only for containerized stdout or log collectors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# src/main/resources/application.yml
spring:
application:
name: order-api
version: 1.0.0
logging:
structured:
format:
console: ecs # Use ecs for container stdout; comment out for local dev
ecs:
service:
environment: homelab
pattern:
correlation: "[${spring.application.name:},%X{traceId:-},%X{spanId:-}] "
include-application-name: false
management:
tracing:
sampling:
probability: 1.0 # 100% for homelab verification; lower in production
opentelemetry:
resource-attributes:
deployment.environment: homelab
logging:
export:
otlp:
endpoint: https://otel.namju.kim/v1/logs
headers:
Authorization: "Bearer ${OTEL_AUTH_TOKEN}"
Setting logging.include-application-name: false avoids duplicating the service name in the plain-text console pattern, since logging.pattern.correlation already includes ${spring.application.name:} alongside traceId and spanId.
Choosing a structured log format
Spring Boot supports three structured logging formats out of the box. All three serialize every key-value pair currently in MDC into top-level JSON fields, so traceId and spanId appear regardless of which format you pick. The real difference comes down to field naming conventions and how well they match your log collector.
| Format | Representative fields | Best-fit ingestion path | When to pick it |
|---|---|---|---|
ecs | @timestamp, log.level, service.name | Filebeat, Elasticsearch, Loki | You already run ELK or want standardized service metadata fields |
logstash | @timestamp, level, logger_name | Logstash, Fluent Bit, Loki | Existing Logstash pipelines and dashboards expect these field names |
gelf | short_message, _level_name | Graylog | Rarely needed unless your team specifically runs Graylog |
| OTLP appender | trace_id, span_id (log record attributes) | OTel Collector → Loki | You want logs and traces flowing through the same collector pipeline |
Because my homelab already has an ELK sandbox alongside Loki, I configure container stdout with ecs and use the OTLP appender on paths where I want direct trace-to-log correlation in Grafana.
When not to use it. Don’t enable JSON formatting on your local development console—raw JSON makes quick debugging painful when a human is reading the terminal. Locally, the default console pattern with logging.pattern.correlation gives you both readability and visible trace IDs. You also shouldn’t switch to JSON on a standalone server with no log aggregator; it burns extra disk space without giving you structured search. Finally, pick one ingestion path to Loki. Shipping both stdout JSON and OTLP logs from the same app duplicates every log entry in storage.
How MDC injection works under the hood
Walking one layer deeper into the request lifecycle makes it clear why traceId appears automatically—and why it sometimes disappears:
ServerHttpObservationFilterintercepts the incoming HTTP request and starts a MicrometerObservation.DefaultTracingObservationHandlerlistens for that start event, creates an OpenTelemetry span, and attaches it to the current thread’s context.- Micrometer Tracing’s
Slf4JEventListenerhooks into the span scope lifecycle, putstraceIdandspanIdinto SLF4J’s MDC when the scope opens, and clears them when the scope closes. - Logback’s structured encoder snapshots the current thread’s MDC at log-event creation time and writes those entries as JSON fields.
Because MDC is backed by ThreadLocal, values only exist on the thread that owns the active span scope. For per-request business identifiers like orderId or userId, I avoid writing to MDC manually. If you forget a MDC.remove() call on a pooled servlet thread, stale values leak into the next unrelated request. SLF4J 2’s fluent API with addKeyValue attaches fields strictly to that single log event instead.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/main/kotlin/kim/namju/order/OrderService.kt
package kim.namju.order
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
@Service
class OrderService {
private val log = LoggerFactory.getLogger(javaClass)
fun place(orderId: Long, userId: Long) {
log.atInfo()
.addKeyValue("orderId", orderId)
.addKeyValue("userId", userId)
.log("Order received")
}
}
If you also want to ship logs over OTLP, you have to wire the Logback appender yourself. Spring Boot auto-configures the OpenTelemetry bean and the OTLP log exporter, but it intentionally leaves Logback appender registration to your application.
1
2
3
4
5
6
7
8
9
<!-- src/main/resources/logback-spring.xml -->
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<appender name="OTEL" class="io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender"/>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="OTEL"/>
</root>
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/main/kotlin/kim/namju/order/config/OtelLogAppenderInstaller.kt
package kim.namju.order.config
import io.opentelemetry.api.OpenTelemetry
import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender
import org.springframework.beans.factory.InitializingBean
import org.springframework.stereotype.Component
@Component
class OtelLogAppenderInstaller(
private val openTelemetry: OpenTelemetry,
) : InitializingBean {
override fun afterPropertiesSet() {
OpenTelemetryAppender.install(openTelemetry)
}
}
Until OpenTelemetryAppender.install(openTelemetry) runs during startup, the appender buffers or drops early boot logs rather than exporting them. Registering it via InitializingBean binds it to Spring’s managed OpenTelemetry instance as soon as the bean is ready.
Verification and caveats
Sending a test request and inspecting the container stdout confirms that ECS fields, MDC correlation IDs, and fluent key-value fields all land in the same JSON object.
1
2
curl -s -X POST http://localhost:8080/orders -H 'Content-Type: application/json' -d '{"userId":7}'
docker logs order-api --tail 1 | jq '{msg: .message, traceId, spanId, orderId}'
1
2
3
4
5
6
{
"msg": "Order received",
"traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
"spanId": "00f067aa0ba902b7",
"orderId": 1042
}
When logs travel through the OTLP path into Loki, trace_id and span_id are stored as structured metadata rather than high-cardinality stream labels. In Grafana Explore, a query like {service_name="order-api"} | trace_id="4bf92f3577b34da6a3ce929d0e0e4736" filters down to every log line emitted during that exact request.
The starter’s default sampling probability is
0.1(10%). Unsampled requests still get atraceIdwritten to MDC, even though the trace is never exported to Tempo. When you see atraceIdin your logs but Tempo returns nothing, sampling is almost always the reason. Keep probability at1.0while verifying your setup locally or in a homelab.
Work dispatched to
@Asyncmethods or a customExecutorServiceruns on a different thread where MDC is empty. IftraceIdvanishes across an async boundary, the bug isn’t in your Logback or JSON config—it’s missing context propagation between threads.
Checklist
Turning on structured logging takes one YAML line, but reliable trace-to-log correlation depends on knowing which thread holds MDC at log time. Before rolling this out, check these five items:
- You picked a single log ingestion path (either stdout JSON or the OTLP appender) to avoid duplicate storage
- The structured format (
ecs,logstash, etc.) matches your existing collector’s field schema - Per-request business keys use SLF4J’s
addKeyValueinstead of manual MDC writes - Local development stays on a human-readable console pattern with correlation IDs
- Your team knows the sampling rate and why a logged
traceIdmay not exist in Tempo when unsampled