Sub topic 12
Structured logging for log aggregation
This chapter assumes you can write SLF4J log statements, set levels in application.properties, and use MDC as covered in earlier chapters. The property examples need Spring Boot 3.4 or later.
Why plain text stops scaling
A default Spring Boot log line is text for humans: timestamp, level, thread, logger, message. That works on a laptop. Once you run ten instances and ship their logs to a central system such as Elasticsearch, Loki, or CloudWatch, text becomes a problem. The aggregator must parse each line with regular expressions, and a stack trace spans many lines that may be stored as separate events.
Structured logging writes each log event as one machine-readable record, usually one JSON object per line. Each piece of data is a named field. You can then query log.level:ERROR AND service.name:orders instead of matching text.
Turning it on
Spring Boot 3.4 added built-in structured logging. You pick a format with one property. No extra dependency is needed.
management.endpoints.web.exposure.include=health,loggers
# Spring Boot 3.4 and later
logging.structured.format.console=ecsThe supported format names are:
| Format | Property value | Typical target |
|---|---|---|
| Elastic Common Schema | `ecs` | Elasticsearch and Kibana |
| Logstash JSON | `logstash` | Logstash pipelines |
| Graylog Extended Log Format | `gelf` | Graylog |
You can also structure the file output with logging.structured.format.file. Console and file can use different formats.
A single event with the ecs format looks like this. The output is shortened and wrapped here for reading. Real output is one line, and the exact fields depend on your Boot version.
{
"@timestamp": "2026-12-01T10:54:02.242Z",
"log.level": "INFO",
"process.pid": 4127,
"process.thread.name": "http-nio-8080-exec-1",
"service.name": "orders",
"log.logger": "com.example.orders.OrderService",
"message": "Placing order A-1001 with 3 items",
"ecs.version": "8.11"
}The message is already formatted from your {} placeholders. The aggregator receives the final text. It does not receive the template and the arguments as separate values.
What changes when structure is on
- The
logging.pattern.consoleandlogging.pattern.fileproperties are ignored for any output that uses a structured format. The JSON layout replaces the pattern. - MDC entries are added to the JSON as fields. The
requestIdset by the filter from the MDC chapter appears on every event without any pattern change. - Exceptions are written as fields inside the same record. A stack trace stays attached to its event, so it is not split across lines.
- Colored output is disabled for structured output, because escape codes would corrupt the JSON.
Describing the service
Aggregators receive logs from many services. Without identity fields you cannot tell which one wrote a line. For ECS and the other formats, Spring Boot can add service metadata:
logging.structured.format.console=ecs
logging.structured.ecs.service.name=orders
logging.structured.ecs.service.version=1.4.2
logging.structured.ecs.service.environment=prod
logging.structured.ecs.service.node-name=${HOSTNAME:local}If you do not set logging.structured.ecs.service.name, Boot falls back to spring.application.name when it is set. Setting spring.application.name is a good habit, because other tools use it as well.
Spring Boot 3.5 added general-purpose properties under logging.structured.json.*. They let you add, exclude, or rename fields in the JSON formats. Check the reference documentation for your exact version before relying on them.
Adding your own fields
Fields from MDC apply to everything logged in a request. For data that belongs to one event, use the SLF4J 2 fluent API with key-value pairs. Boot's structured formats write them as fields.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class PaymentService {
private static final Logger log = LoggerFactory.getLogger(PaymentService.class);
public void charge(String orderId, long amountCents) {
log.atInfo()
.addKeyValue("orderId", orderId)
.addKeyValue("amountCents", amountCents)
.log("Payment captured");
}
}In the aggregator, orderId and amountCents become separately searchable fields. You can filter on amountCents > 100000 without parsing the message. The same call under a plain text pattern ignores the key-value pairs unless you add them to the pattern, so check which format each environment uses.
MDC or key-value pairs
| Use | When |
|---|---|
| MDC | The value applies to every log line in a scope, such as request ID, user ID, or tenant. |
| Key-value pair | The value belongs to one event, such as an amount or a result code. |
Writing a custom format
If none of the built-in formats fits, implement StructuredLogFormatter for your backend. For Logback the event type is ILoggingEvent:
package com.example.logging;
import ch.qos.logback.classic.spi.ILoggingEvent;
import org.springframework.boot.logging.structured.StructuredLogFormatter;
public class KeyValueFormatter implements StructuredLogFormatter<ILoggingEvent> {
@Override
public String format(ILoggingEvent event) {
return "time=" + event.getInstant()
+ " level=" + event.getLevel()
+ " logger=" + event.getLoggerName()
+ " message=" + event.getFormattedMessage()
+ "\n";
}
}Select it by its fully qualified class name:
logging.structured.format.console=com.example.logging.KeyValueFormatterThe returned string is written as-is, so you must add the line ending yourself. This example does no escaping. A message containing a quote or newline will break a line-based parser. For JSON, prefer a built-in format.
Before Spring Boot 3.4
Older versions have no logging.structured.* properties. The usual approach is the logstash-logback-encoder library with a logback-spring.xml that configures a LogstashEncoder on the appender. The result is similar. The cost is an extra dependency and your own XML to maintain. If you can upgrade, the built-in support is simpler.
Operational points
- Log to stdout in containers. Write structured events to the console and let the platform's collector ship them. Writing JSON files inside a container adds rotation and disk concerns for no gain.
- Keep one format per environment. Developers often prefer readable text locally. Use profiles from the profile chapter so
devkeeps the normal pattern andprodsets the structured format:
# application-prod.properties
logging.structured.format.console=ecs
logging.structured.ecs.service.environment=prod- Watch field cardinality. Fields with unbounded distinct values, such as a UUID in every message, are fine as searchable fields. Some aggregators, however, index every field name, so do not create field names from data (for example
user_1234=...). - Sensitive data is still sensitive. Structure makes fields easier to find, including passwords and tokens. Never put them in messages, MDC, or key-value pairs.
- Timestamps are UTC instants. Check that your aggregator reads the timestamp field. Otherwise it may use the arrival time, which shifts events when collectors lag.
Common mistakes
- Setting
logging.pattern.consoleand expecting it to change JSON output. It has no effect once a structured format is active. - Mixing plain-text and JSON lines in one stream. Parsers often drop the plain lines or flag the whole stream. Library startup banners are a common source, so consider
spring.main.banner-mode=offin production. - Adding MDC values in a filter without removing them. The next request on the same pooled thread then inherits stale fields.
- Building a JSON string by hand in the log message. The result is a JSON string nested inside a JSON field. Use key-value pairs instead.
Exercise
Your service runs in a container, and its logs are shipped to Elasticsearch. Which properties would you set for production so that events are ECS JSON on the console, identify the service as "billing" version 2.0.1, and include the request ID that your filter stores in MDC under the key requestId? What do you need to do for the request ID?
Show answer
Set logging.structured.format.console=ecs, logging.structured.ecs.service.name=billing, and logging.structured.ecs.service.version=2.0.1, for example in application-prod.properties. Nothing more is needed for the request ID: the structured formats write MDC entries as fields automatically, so requestId appears on every event as long as the filter puts it in MDC and removes it in a finally block. A %X{requestId} pattern is not needed, because the pattern properties are ignored when a structured format is active.