Skip to lesson

Logback configuration and log files

ShopLite needs readable lines on a developer's screen, but on the server it needs files that never fill the disk and that tools can search. Changing that must not mean touching a single log.info call.

logging.level and logging.file.name

Logging properties are settings in application.properties, such as logging.level.* and logging.file.name, with which Spring Boot configures Logback without any XML.

Two properties already cover many apps: one sets the levels, the other adds a log file next to the console.

Example 1 · src/main/resources/application.properties (levels and a log file)

Runs in: the shoplite-api Spring Boot project

Properties
logging.level.root=warnlogging.level.com.shoplite=infologging.file.name=logs/shoplite.log
Sample output
$ java -jar target/shoplite-api-1.2.0.jar
... the usual console lines ...

$ ls logs
shoplite.log

$ ls logs                     # a few days later, on a busy server
shoplite.2026-10-14.0.gz  shoplite.2026-10-15.0.gz  shoplite.2026-10-15.1.gz  shoplite.log

What this code does

  • logging.file.name adds a file next to the console; the folder is created when needed. Paths are relative to the folder you start the app from.
  • Old days are renamed with the date and a counter and compressed, by Boot's default pattern ${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz. October 15 needed two files because it passed 10 MB.

logging.level.<package> sets levels, as in the first lesson. logging.file.name makes Boot also write every line to that file.

Boot's file output already rolls: when the file reaches 10 MB it is renamed with the date and a number, gzipped, and a new file starts. The logging.logback.rollingpolicy.* properties change the size, how many days are kept and the total size.

logback-spring.xml: appenders, encoders and patterns

An appender is one log destination, such as the console or a file. In java.util.logging the same idea is called a handler.

The file below defines two appenders, each with its own pattern, and lets each profile pick which one the root logger uses.

One log call becomes output in steps. The call log.info goes to the logger, which checks its level. Each appender on the logger then gets the event. CONSOLE formats it with its encoder pattern and prints it. FILE uses its own encoder, writes logs/shoplite.log and rolls the file.

Example 2 · src/main/resources/logback-spring.xml

Runs in: the shoplite-api Spring Boot project

XML
<?xml version="1.0" encoding="UTF-8"?><!-- src/main/resources/logback-spring.xml --><configuration>    <!-- Folder for log files: the LOG_DIR environment variable, or "logs" -->    <property name="LOG_DIR" value="${LOG_DIR:-logs}"/>    <!-- Appender 1: readable lines on the console -->    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">        <encoder>            <pattern>%d{HH:mm:ss.SSS} %-5level [%X{requestId:-none}] %logger{30} - %msg%n</pattern>        </encoder>    </appender>    <!-- Appender 2: a file that rolls every day and every 10 MB, kept for 30 days, 1 GB at most -->    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">        <file>${LOG_DIR}/shoplite.log</file>        <encoder>            <pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5level [%X{requestId:-none}] [%thread] %logger{40} - %msg%n</pattern>        </encoder>        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">            <fileNamePattern>${LOG_DIR}/shoplite.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>            <maxFileSize>10MB</maxFileSize>            <maxHistory>30</maxHistory>            <totalSizeCap>1GB</totalSizeCap>        </rollingPolicy>    </appender>    <!-- dev: detail from ShopLite, on the console -->    <springProfile name="dev">        <logger name="com.shoplite" level="DEBUG"/>        <root level="INFO">            <appender-ref ref="CONSOLE"/>        </root>    </springProfile>    <!-- prod: ShopLite at INFO, libraries at WARN, into the rolling file -->    <springProfile name="prod">        <logger name="com.shoplite" level="INFO"/>        <root level="WARN">            <appender-ref ref="FILE"/>        </root>    </springProfile></configuration>
Sample output
$ java -jar target/shoplite-api-1.2.0.jar --spring.profiles.active=prod
$ tail -2 logs/shoplite.log
2026-10-16T10:42:01.262+05:30 INFO  [f2b8] [http-nio-8080-exec-4] com.shoplite.order.OrderService - Order 18 placed by customer 7, total 1598.00
2026-10-16T10:42:11.249+05:30 ERROR [a1f3] [http-nio-8080-exec-2] com.shoplite.payment.PaymentService - Payment failed for order 17 (Rs 499.00)

What this code does

  • Two appenders, each with its own encoder and pattern. <springProfile> picks which ones the root logger uses: the console in dev, the rolling file in prod.
  • ${LOG_DIR:-logs} reads an environment variable or system property with a default, so the server can move the logs without a rebuild. <logger name="com.shoplite" level="INFO"/> has no appender of its own; its lines flow up to the root's appender.

Example 3 · Handlers and formatters: appenders and encoders in plain Java

TwoOutputsDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.logging.FileHandler;import java.util.logging.Formatter;import java.util.logging.Handler;import java.util.logging.Level;import java.util.logging.LogRecord;import java.util.logging.Logger;import java.util.logging.StreamHandler;
/** Encoder 1: a short line for people. */class ReadableFormatter extends Formatter {    @Override    public String format(LogRecord r) {        return String.format("%-7s %s - %s%n", r.getLevel(), r.getLoggerName(), formatMessage(r));    }}
/** Encoder 2: one JSON object per line for log tools (real ones add a timestamp too). */class JsonFormatter extends Formatter {    @Override    public String format(LogRecord r) {        return String.format("{\"level\":\"%s\",\"logger\":\"%s\",\"message\":\"%s\"}%n",                r.getLevel(), r.getLoggerName(), formatMessage(r).replace("\"", "\\\""));    }}
public class TwoOutputsDemo {    private static final Logger ORDERS = Logger.getLogger("com.shoplite.order");    private static final Logger log = Logger.getLogger("com.shoplite.order.OrderService");
    public static void main(String[] args) throws IOException {        Path dir = Files.createTempDirectory("shoplite-logs");        Path file = dir.resolve("shoplite.json.log");
        ORDERS.setUseParentHandlers(false);          // only our two outputs        ORDERS.setLevel(Level.FINE);
        Handler console = new StreamHandler(System.out, new ReadableFormatter()) {            @Override            public synchronized void publish(LogRecord r) {                super.publish(r);                flush();            }        };        console.setLevel(Level.INFO);                // appender 1: console, INFO and up
        FileHandler json = new FileHandler(file.toString());        json.setFormatter(new JsonFormatter());        json.setLevel(Level.FINE);                   // appender 2: file, DEBUG (FINE) and up
        ORDERS.addHandler(console);        ORDERS.addHandler(json);
        log.fine("Cart of customer 7 has 2 lines");        log.info("Order 18 placed by customer 7");        log.warning("Stock of MOB-IP15 is low: 2 left");        json.close();
        System.out.println("--- " + file.getFileName() + " ---");        Files.readAllLines(file).forEach(System.out::println);
        Files.delete(file);        Files.delete(dir);    }}
Output
INFO    com.shoplite.order.OrderService - Order 18 placed by customer 7
WARNING com.shoplite.order.OrderService - Stock of MOB-IP15 is low: 2 left
--- shoplite.json.log ---
{"level":"FINE","logger":"com.shoplite.order.OrderService","message":"Cart of customer 7 has 2 lines"}
{"level":"INFO","logger":"com.shoplite.order.OrderService","message":"Order 18 placed by customer 7"}
{"level":"WARNING","logger":"com.shoplite.order.OrderService","message":"Stock of MOB-IP15 is low: 2 left"}

What this code does

  • One logger, two outputs with different levels and formats: people read the short console lines, tools read the JSON file, which also holds the FINE (debug) line.
  • This is the same split Logback makes: a Handler is an appender, a Formatter is an encoder. setUseParentHandlers(false) stops lines from also reaching the root logger's default console handler.

Three building blocks: an appender is one destination; an encoder turns an event into bytes, usually with a pattern; a logger element sets a level and links to appenders. The root logger is the parent of all.

Name the file logback-spring.xml, not logback.xml: with the -spring name Boot loads it itself, so Spring features such as <springProfile> work and logging.level.* properties still apply. Example 3 shows the same ideas in plain Java, where they are called a handler and a formatter.

Find the bug

Spot the config bug

Tap the line that causes the problem.

The app starts, but nothing is printed on the console. Which line?

Round 1 of 2

Rolling files by size and date

Rolling means closing a log file by date or size and starting a new one, so one file never fills the disk.

Four properties set the file's place, the size of one file, how many days are kept and the total size.

Properties
logging.file.name=logs/shoplite.loglogging.logback.rollingpolicy.max-file-size=10MBlogging.logback.rollingpolicy.max-history=30logging.logback.rollingpolicy.total-size-cap=1GB

Example 4 · Rolling by size, keeping only the newest files

RollingFilesDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;import java.util.logging.FileHandler;import java.util.logging.Formatter;import java.util.logging.LogRecord;import java.util.logging.Logger;import java.util.stream.Stream;
public class RollingFilesDemo {    private static final Logger log = Logger.getLogger("com.shoplite.order.OrderService");
    public static void main(String[] args) throws IOException {        Path dir = Files.createTempDirectory("shoplite-logs");        // %g = generation number. Roll after about 120 bytes, keep 3 files: shoplite.0.log is the newest.        FileHandler rolling = new FileHandler(dir.resolve("shoplite.%g.log").toString(), 120, 3);        rolling.setFormatter(new Formatter() {            @Override            public String format(LogRecord r) {                return r.getMessage() + "\n";            }        });        log.setUseParentHandlers(false);        log.addHandler(rolling);
        for (int order = 17; order <= 30; order++) {            log.info("Order " + order + " placed by customer " + (order % 5 + 1));   // 30-31 bytes a line        }        rolling.close();
        List<Path> files;        try (Stream<Path> s = Files.list(dir)) {            files = s.filter(p -> p.toString().endsWith(".log")).sorted().toList();        }        for (Path f : files) {            List<String> lines = Files.readAllLines(f);            System.out.printf("%-14s %3d bytes  %s ... %s%n", f.getFileName(), Files.size(f),                    lines.get(0).substring(0, 8), lines.get(lines.size() - 1).substring(0, 8));        }        System.out.println("Orders 17 to 20 are gone: only 3 files are kept.");
        try (Stream<Path> s = Files.list(dir)) {            for (Path p : s.toList()) {                Files.delete(p);                       // also the .lck lock file, if left            }        }        Files.delete(dir);    }}
Output
shoplite.0.log  60 bytes  Order 29 ... Order 30
shoplite.1.log 120 bytes  Order 25 ... Order 28
shoplite.2.log 120 bytes  Order 21 ... Order 24
Orders 17 to 20 are gone: only 3 files are kept.

What this code does

  • JUL's FileHandler(pattern, limit, count) rolls by size like Logback's maxFileSize: when a file reaches 120 bytes it moves to the next number and a new .0 file starts.
  • With count 3, only three files exist, so the oldest lines (orders 17 to 20) are deleted. Logback's maxHistory and totalSizeCap limit old files in the same spirit, by days and by total size.

SizeAndTimeBasedRollingPolicy rolls at midnight and whenever a file reaches maxFileSize. Its fileNamePattern needs both %d{...} (the date) and %i (a counter within the day); ending it in .gz compresses old files.

maxHistory keeps that many days of old files and totalSizeCap limits their total size. When both are set, whichever is reached first wins: on a busy sale day a 1 GB cap may keep only three days, not thirty.

Profile-specific logging and JSON logs

A structured log writes each event as one JSON object, so tools can filter by field such as level, logger or requestId.

On servers, logs are read by tools such as Elasticsearch, Loki and CloudWatch, not by people. One property switches the console to JSON.

Example 5 · src/main/resources/application-prod.properties (JSON logs)

Runs in: the shoplite-api Spring Boot project

Properties
logging.level.com.shoplite=infologging.structured.format.console=ecs
Sample output (one line, wrapped by the page)
{"@timestamp":"2026-10-16T05:12:01.262Z","log":{"level":"INFO","logger":"com.shoplite.order.OrderService"},"process":{"pid":14872,"thread":{"name":"http-nio-8080-exec-4"}},"service":{"name":"shoplite-api","version":"1.2.0","node":{}},"message":"Order 18 placed by customer 7, total 1598.00","requestId":"f2b8","ecs":{"version":"8.11"}}

What this code does

  • ECS (Elastic Common Schema) is a standard set of JSON field names. Each event is one line, so a tool can search requestId:f2b8 AND log.level:ERROR without any text parsing.
  • The MDC value requestId from the filter appears as its own field. Because this setting is only in the prod profile, developers keep readable lines in dev.

A profile is a named set of settings, such as dev or prod. Put levels and outputs that differ in application-dev.properties and application-prod.properties, or wrap parts of logback-spring.xml in <springProfile name="prod">.

Since Spring Boot 3.4 one property does the JSON: logging.structured.format.console=ecs (also gelf or logstash). MDC values become JSON fields automatically.

Next step

Check your understanding

10 quick questions