Sub topic 9
Taking control with logback-spring.xml
Properties in application.properties cover most logging needs. Some things they cannot express: several appenders with different filters, a separate file for one package, or settings that depend on the active profile. For those, you write a Logback configuration file.
This chapter assumes you can write log statements with SLF4J, set levels through properties, and configure console and file output with the logging.* properties. It also assumes you know what a Spring profile is.
Why the file is called logback-spring.xml
Logback looks for configuration files in this order on the classpath: logback-test.xml, logback.xml, and a few others. Spring Boot adds support for logback-spring.xml. Spring Boot reads this file after it has built the Spring Environment, so the file can use Spring-only features such as <springProfile> and <springProperty>.
If you name the file logback.xml, Logback loads it very early, before Spring is ready. Then the Spring extensions fail with errors, and Spring Boot warns you about it. Use logback-spring.xml and put it in src/main/resources.
You can also point to a different file with the logging.config property, for example logging.config=classpath:custom-logback.xml.
The parts of a Logback configuration
Every Logback file is built from three kinds of element.
| Element | Role |
|---|---|
| `<appender>` | A destination for log events, such as the console or a file |
| `<encoder>` or `<layout>` | Turns an event into text, using a pattern |
| `<logger>` and `<root>` | Choose a level and which appenders receive events |
A <logger> is attached to a package or class name. <root> is the parent of all loggers. An event goes to the appenders of its logger, then travels up to the parents' appenders. This upward flow is called additivity. It is the reason a log line sometimes appears twice, as the pitfalls section below explains.
Reusing Spring Boot's defaults
You do not have to write everything from scratch. Spring Boot ships fragments that you can include:
org/springframework/boot/logging/logback/defaults.xmldefines the conversion rules (such as%clrfor color) and default patterns, and sets levels for noisy libraries.org/springframework/boot/logging/logback/console-appender.xmldefines an appender namedCONSOLE.org/springframework/boot/logging/logback/file-appender.xmldefines an appender namedFILE.
Because these fragments read the same logging.* properties you already know, your property settings keep working.
A minimal file with profiles
The following file includes the defaults and picks a different root level for each profile. It is the example to start from.
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<springProfile name="dev">
<root level="DEBUG">
<appender-ref ref="CONSOLE"/>
</root>
</springProfile>
<springProfile name="prod">
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</springProfile>
</configuration>Read it from the top:
- The two
<include>lines load the defaults and create theCONSOLEappender. <springProfile name="dev">makes everything inside it apply only when thedevprofile is active.- Inside,
<root>sets the level and connects theCONSOLEappender with<appender-ref>.
An appender that is defined but never referenced by any logger does nothing. If you start the application with a profile other than dev or prod, this file configures no root logger at all, and nothing is logged. The next sections show how to avoid that.
Profile expressions
The name attribute accepts more than one profile and simple logic:
name="dev,test"matches if either profile is active.name="!prod"matches wheneverprodis not active.name="staging & eu"matches only when both are active. The&form needs parentheses when mixed with|.
A safe pattern is to configure a default outside any <springProfile> block, then override it for specific profiles:
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
<springProfile name="dev">
<logger name="com.example.orders" level="DEBUG"/>
</springProfile>
</configuration>Here every profile gets an INFO root with console output. Only dev raises one package to DEBUG. The <logger> element has no <appender-ref>, so its events flow up to the root and use the console appender once.
Reading Spring properties with springProperty
<springProperty> copies a value from the Spring Environment into a Logback variable. This lets one setting drive both Spring and Logback.
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<springProperty scope="context" name="appName" source="spring.application.name" defaultValue="app"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} ${appName} %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>The source attribute names the Spring property. defaultValue is used when the property is missing. After that, ${appName} works like any Logback variable.
Writing your own rolling file appender
The logging.logback.rollingpolicy.* properties handle common rolling. When you need two files, such as a general log and an audit log, define the appenders yourself.
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<appender name="AUDIT" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/audit.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>logs/audit.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
<maxFileSize>10MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>1GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %msg%n</pattern>
</encoder>
</appender>
<logger name="com.example.audit" level="INFO" additivity="false">
<appender-ref ref="AUDIT"/>
</logger>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>Points to notice:
SizeAndTimeBasedRollingPolicystarts a new file each day, and also when a file passes 10 MB. The%iin the file name is the counter for several files in one day. The.gzending makes Logback compress rolled files.maxHistoryis counted in days here, because the date pattern rolls daily.totalSizeCapdeletes the oldest archives when the total passes the limit. It protects the disk.additivity="false"on the audit logger stops its events from also reaching the root's console appender. Without it, audit lines would appear on the console too.
How Boot and Logback fit together at startup
The first lines your application prints appear before the final configuration exists. That is why very early messages can have a different format from later ones.
Common pitfalls
- Duplicate lines. A logger with its own
<appender-ref>toCONSOLE, while root also usesCONSOLE, prints each event twice. Either drop the<appender-ref>or setadditivity="false". - No output at all. A root logger is missing for the active profile, as in the first example when you run with another profile.
- Wrong file name.
logback.xmlinstead oflogback-spring.xmlgives errors for<springProfile>. - File is ignored. It is not in
src/main/resources, so it never reaches the classpath. Checktarget/classesorbuild/resources/main. - Properties stop working. If you write your own appenders without including Boot's fragments,
logging.pattern.*andlogging.file.namehave no effect on them. This is expected, because only Boot's fragments read those properties. - Silent mistakes. Logback prints its own configuration problems as status messages. Add
debug="true"to<configuration>while you troubleshoot, and remove it afterwards.
Choosing between properties and XML
Start with properties. Move to logback-spring.xml only when you need something properties cannot do: more than one file, filters, different appenders per profile, or values taken from the Environment. The XML file adds a second place where logging is configured, so keep it short and let the included fragments do the common work.
Exercise
Your application runs with the profile staging. Your logback-spring.xml contains the two <springProfile> blocks for dev and prod from the first example, and nothing else except the includes. You see no log output. Why, and how do you fix it with the fewest changes?
Show answer
No <root> element applies when the active profile is staging, so no appender is attached to any logger. Fix it by adding a default <root level="INFO"> with <appender-ref ref="CONSOLE"/> outside the <springProfile> blocks, and keep the profile blocks only for the overrides. Alternatively, use <springProfile name="!dev & !prod">, but a default root is simpler and safer.
Exercise
You added a logger com.example.audit with <appender-ref ref="AUDIT"/>, and audit lines now appear in both audit.log and on the console. Which attribute do you change, and to what?
Show answer
Set additivity="false" on that <logger> element. This stops its events from also passing to the root logger's appenders, including the console.