Video in progress
How do you configure Spring Boot logging so logs are plain text locally and JSON in production?
In Spring Boot 3.4+, switching to JSON is a single setting, logging.structured.format.console (ecs, logstash or gelf), and you put it in the prod profile. In older versions you separate the appenders with <springProfile> inside logback-spring.xml.
📖 Answer
In production, logs are collected by Loki, ELK or another system, and they handle JSON well: level, traceId and userId become separate searchable fields. In a local terminal, though, JSON is awkward to read.
The simple way from Boot 3.4:
# application-prod.yml
logging:
structured:
format:
console: ecs
In older versions you write logback-spring.xml (with exactly the -spring suffix, otherwise <springProfile> doesn't work):
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<springProfile name="!prod">
<root level="INFO"><appender-ref ref="CONSOLE"/></root>
</springProfile>
<springProfile name="prod">
<appender name="JSON" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="net.logstash.logback.encoder.LogstashEncoder"/>
</appender>
<root level="INFO"><appender-ref ref="JSON"/></root>
</springProfile>
</configuration>
LogstashEncoder comes from a separate library (logstash-logback-encoder).
A few practical points. The traceId in MDC lands in the JSON automatically as a field, while in the text format you add it to the pattern yourself. Control log levels through logging.level.*, not in the XML, so you can change them at runtime with Actuator's /loggers. Don't leave both logback.xml and logback-spring.xml: the first is loaded before Boot and causes confusion.
Sign up to mark studied questions and save your progress.