Video in progress
How do you separate Logback configuration by environment, and why is `logback-spring.xml` recommended over `logback.xml` in Spring Boot?
logback.xml is loaded by Logback itself, before the Spring context, and knows nothing about profiles or application.yml values. Spring Boot loads logback-spring.xml itself, so <springProfile> and <springProperty> work.
📖 Answer
A typical requirement: colored plain-text logs locally, JSON to stdout only in prod. With a plain logback.xml you would have to play with system properties to do that. With logback-spring.xml:
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<springProperty name="APP" source="spring.application.name" defaultValue="app"/>
<springProfile name="local">
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<root level="INFO"><appender-ref ref="CONSOLE"/></root>
</springProfile>
<springProfile name="!local">
<appender name="JSON" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<customFields>{"service":"${APP}"}</customFields>
</encoder>
</appender>
<root level="INFO"><appender-ref ref="JSON"/></root>
</springProfile>
</configuration>
Why this matters: Logback starts very early. If it finds logback.xml, it loads it completely before Spring Boot starts, and it clashes with some of Boot's logging.* properties. The file with the -spring suffix is loaded through Boot's LoggingSystem, once the environment is ready.
In most cases you don't need XML at all: logging.level.*, logging.pattern.* and, on Boot 3.4+, logging.structured.format.console are enough. I only reach for XML when I need a custom appender, a filter or async settings.
One trap: the name expressions inside <springProfile> (!local, prod & eu) work, but when no profile is active the !local block applies. You may get JSON locally too and wonder why.
Sign up to mark studied questions and save your progress.