Sub topic 9
Configuring Logback
This chapter assumes you can add Maven dependencies, you know the SLF4J Logger API from the earlier chapters, and you know that SLF4J needs a provider at runtime. Here you will set up Logback, the most common SLF4J provider, so that you control where log lines go, how they look, and which ones are kept.
How Logback finds its configuration
Logback reads its configuration once, when the first logger is created. It looks for these sources in order and uses the first one it finds:
- The file or URL named by the system property
logback.configurationFile. logback-test.xmlon the classpath.logback.xmlon the classpath.- A built-in default.
The built-in default prints everything at DEBUG and above to the console. This is why an unconfigured application can be very noisy, and why libraries that log at DEBUG become visible without anyone asking for them.
logback-test.xml takes priority over logback.xml. A common pattern is to put logback-test.xml in src/test/resources so tests get their own settings, while logback.xml in src/main/resources serves production.
The three building blocks
A Logback configuration is built from three kinds of elements.
| Element | Role | Example |
|---|---|---|
| Appender | Writes log events to a destination | `ConsoleAppender`, `RollingFileAppender` |
| Encoder | Turns an event into bytes for an appender | `PatternLayoutEncoder` |
| Logger | Selects events by name and level, and chooses appenders | `<logger name="com.example.payments">` |
An appender does not decide which events it receives. Loggers do that, by attaching appenders with <appender-ref>.
A first complete configuration
The dependencies are the ones from the previous chapter: slf4j-api for compiling and logback-classic at runtime. This logback.xml sends everything at INFO and above to the console, and enables DEBUG for one package.
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.example.payments" level="DEBUG"/>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>Each part does one job:
- The
<appender>namedCONSOLEwrites to standard output. - The
<pattern>describes each line.%d{HH:mm:ss.SSS}is the time,%-5levelis the level padded to five characters,%threadis the thread name,%logger{36}is the logger name shortened to about 36 characters,%msgis the message and%nis a line break. <root>is the top of the logger hierarchy. Its level isINFOand it has the console appender.- The
<logger>forcom.example.paymentssets only a level. It has no appender of its own.
An exception passed to a log call is printed after the message automatically. If your pattern does not contain an exception converter, Logback appends %ex for you. You can write %ex{short} or %rEx (root cause first) if you want different stack trace output.
Logger hierarchy, levels and additivity
Logger names form a tree separated by dots. The logger com.example.payments.CardService is a child of com.example.payments, which is a child of com.example, and so on up to the root.
Two rules govern how an event travels through that tree.
- Level inheritance. A logger with no level uses the level of its nearest ancestor that has one.
com.example.payments.CardServicehas no level in the file above, so it inheritsDEBUGfromcom.example.payments. - Additivity. After a logger handles an event, the event also goes to the appenders of all its ancestors. This is on by default.
The level check uses only the level of the logger that receives the call. The ancestors' levels are not checked again. Only their appenders matter.
Additivity causes the most common configuration bug: duplicated lines. If you attach the CONSOLE appender to com.example.payments and also to the root, each event from that package prints twice. Either remove the extra <appender-ref> or turn off additivity:
<logger name="com.example.payments" level="DEBUG" additivity="false">
<appender-ref ref="PAYMENTS_FILE"/>
</logger>With this setting, payment events go only to PAYMENTS_FILE and never reach the root's console appender.
Writing to rolling files
A plain FileAppender grows without limit. RollingFileAppender starts a new file on a schedule or size boundary and deletes old files.
<configuration>
<property name="LOG_DIR" value="${LOG_DIR:-logs}"/>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_DIR}/app.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIR}/app.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
<maxFileSize>10MB</maxFileSize>
<maxHistory>14</maxHistory>
<totalSizeCap>1GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>%d{ISO8601} %-5level [%thread] %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="FILE"/>
</root>
</configuration>Points to notice:
${LOG_DIR:-logs}reads a system property or environment variable namedLOG_DIRand falls back tologsif it is not set. The:-syntax is the default-value form.%d{yyyy-MM-dd}in the file name makes the policy roll daily.%iis a counter that distinguishes several files on the same day once one exceedsmaxFileSize.- The
.gzsuffix makes Logback compress the archived files. maxHistoryis counted in rollover periods, which here means days.totalSizeCapdeletes the oldest archives when the total gets too large.
Using several appenders and an async wrapper
A logger can have any number of appenders. A typical production setup writes human-readable lines to the console and everything to a file. Appender references are listed in the root or in a <logger>:
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ASYNC_FILE"/>
</root>ASYNC_FILE is an AsyncAppender that wraps the file appender. The calling thread puts the event on a queue and returns. A separate thread does the disk write.
<appender name="ASYNC_FILE" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>1024</queueSize>
<discardingThreshold>0</discardingThreshold>
<neverBlock>false</neverBlock>
<appender-ref ref="FILE"/>
</appender>The settings matter:
- By default, once the queue is 80 percent full,
AsyncAppendersilently discards events atTRACE,DEBUGandINFO. SettingdiscardingThresholdto0keeps them. - With
neverBlockset tofalse, callers wait when the queue is full, so no events are lost but latency can rise. Withtrue, callers never wait and events are dropped instead. - Events still in the queue can be lost if the JVM exits abruptly. See the shutdown note below.
Changing configuration without a restart
Setting scan="true" makes Logback check the file for changes, by default once a minute:
<configuration scan="true" scanPeriod="30 seconds">
...
</configuration>This allows you to raise one package to DEBUG on a running server by editing the file. The cost is a small check on logging activity, so use it where the file is under your control and leave it off elsewhere.
Verifying your setup
This program logs at several levels from two loggers. Run it with the first configuration above on the classpath.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConfigDemo {
private static final Logger app =
LoggerFactory.getLogger("com.example.app.Main");
private static final Logger payments =
LoggerFactory.getLogger("com.example.payments.CardService");
public static void main(String[] args) {
app.debug("app debug");
app.info("app info");
payments.debug("payments debug");
payments.info("payments info");
}
}The output has three lines. app debug is dropped, because com.example.app.Main inherits INFO from the root. payments debug appears, because com.example.payments.CardService inherits DEBUG from com.example.payments. Lines look like 06:44:31.874 DEBUG [main] c.e.payments.CardService - payments debug.
If the output is not what you expect, check these in order:
- Is
logback.xmlat the root of the classpath, such assrc/main/resources? A file in the wrong folder is ignored without error. - Is there a
logback-test.xmloverriding it? - Do you have more than one SLF4J provider on the classpath? SLF4J warns about multiple providers and picks one.
- Did you enable
debug="true"and read the status messages?
Common mistakes
- Duplicate lines. An appender is attached both to a logger and to the root, and additivity is on.
- A level set on an appender instead of a logger. Appenders can be given a threshold filter, but the usual place for levels is the logger. Setting both makes it hard to see why a line is missing.
- Secrets in the pattern or message. Configuration controls format, not content. Whatever is passed to
log.infoends up in the file. - Leaving the default configuration in production. The default
DEBUGconsole output is rarely what you want. Ship alogback.xml. - Expecting changes to take effect without
scan. Edits are read only at startup unless scanning is on.
Exercise
A configuration has <logger name="com.example.payments" level="DEBUG"><appender-ref ref="CONSOLE"/></logger> and <root level="INFO"><appender-ref ref="CONSOLE"/></root>. A class in com.example.payments logs one message at INFO. How many lines appear, and what is the smallest change to get one line?
Show answer
Two lines appear. The event goes to the logger's CONSOLE appender, and with additivity on, it also goes to the root's CONSOLE appender. Either remove the <appender-ref> from the com.example.payments logger, so it only sets a level, or add additivity="false" to that logger.
Exercise
You want logs written to logs/app.2026-11-26.0.log.gz style archives, rolled daily and also when a file reaches 10 MB, keeping 14 days. Which rolling policy and settings do you use?
Show answer
Use RollingFileAppender with SizeAndTimeBasedRollingPolicy. Set fileNamePattern to logs/app.%d{yyyy-MM-dd}.%i.log.gz, maxFileSize to 10MB and maxHistory to 14. The %i counter is required, and the .gz suffix turns on compression.
Exercise
With the default AsyncAppender settings, why might INFO lines go missing under heavy load, and how do you prevent it?
Show answer
When the queue is 80 percent full, the default discardingThreshold makes the appender discard TRACE, DEBUG and INFO events. Set discardingThreshold to 0 to keep them. Then choose neverBlock deliberately: false makes callers wait when the queue is full, and true drops events instead.