Logging in Spring Boot: from the default format to JSON

Spring Boot logs through SLF4J and Logback with no setup, and configures both from application properties. This page runs the default format, levels and groups, placeholder costs, exception logging, MDC across threads, structured JSON output, logback-spring.xml and a switch to Log4j 2, explaining every line they print.

Contents

How logging fits together in Spring Boot

Logging in a Java application has two layers. Your code talks to a facade, an API with methods such as log.info(...) that does not write anything itself. A logging backend behind it decides which messages pass, formats them and writes them to the console, a file or a log shipper. Keeping the two apart means libraries can log without forcing a backend on the application.

Spring Boot picks both for you. spring-boot-starter-logging, which every starter pulls in, brings:

  • SLF4J: the facade your code uses, through LoggerFactory.getLogger(...).
  • Logback: the default backend.
  • Bridges: jul-to-slf4j and log4j-to-slf4j redirect java.util.logging and the Log4j 2 API into SLF4J, so messages from every library end up in one place. Spring's own classes log through Commons Logging, which reaches the same backend.

On top of the backend, Spring Boot adds its LoggingSystem. It configures Logback before the application context starts, reads the logging.* properties, and lets levels be changed at runtime. That is why logging.level.com.example=DEBUG in application.properties works without any Logback XML.

Log levels, from most to least detailed
LevelUse forOn by default
TRACEVery fine detail: each loop step, each SQL parameterNo
DEBUGDiagnostic detail for developersNo
INFONormal milestones: started, order placedYes
WARNSomething unexpected that the application handledYes
ERRORA failure that needs attentionYes

A logger passes a message when the message's level is at or above the logger's level. Loggers form a tree by name: com.shop.orders.OrderService inherits from com.shop.orders, then com.shop, then the root logger, unless a level is set somewhere on the way. All programs on this page run Spring Boot 4.1.2 with Logback 1.5.

The default console format

With no logging configuration at all, a small application logs its startup and five messages, one per level, the last one with an exception:

Java
package logging.defaults;

import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DefaultFormat {

    private static final Logger log = LoggerFactory.getLogger(DefaultFormat.class);

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(DefaultFormat.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "spring.application.name", "orders"));
        try (var context = app.run(args)) {
            log.info("application {} ready", context.getEnvironment()
                    .getProperty("spring.application.name"));
            log.trace("trace is below the default INFO level");
            log.debug("debug is below the default INFO level");
            log.info("order {} placed for {} items", 1042, 3);
            log.warn("stock for {} is low: {}", "BOOK-7", 2);
            log.error("payment failed", new IllegalStateException("card declined"));
        }
    }
}
Output
2026-11-15T07:33:40.149-05:00  INFO 31731 --- [orders] [           main] logging.defaults.DefaultFormat           : Starting DefaultFormat using Java 21.0.12.1 with PID 31731 (/tmp/claude-0/jv/spring/sb/SpringLogging/out started by root in /tmp/claude-0/jv)
2026-11-15T07:33:40.152-05:00  INFO 31731 --- [orders] [           main] logging.defaults.DefaultFormat           : No active profile set, falling back to 1 default profile: "default"
2026-11-15T07:33:40.664-05:00  INFO 31731 --- [orders] [           main] logging.defaults.DefaultFormat           : Started DefaultFormat in 0.941 seconds (process running for 1.294)
2026-11-15T07:33:40.670-05:00  INFO 31731 --- [orders] [           main] logging.defaults.DefaultFormat           : application orders ready
2026-11-15T07:33:40.671-05:00  INFO 31731 --- [orders] [           main] logging.defaults.DefaultFormat           : order 1042 placed for 3 items
2026-11-15T07:33:40.671-05:00  WARN 31731 --- [orders] [           main] logging.defaults.DefaultFormat           : stock for BOOK-7 is low: 2
2026-11-15T07:33:40.671-05:00 ERROR 31731 --- [orders] [           main] logging.defaults.DefaultFormat           : payment failed

java.lang.IllegalStateException: card declined
	at logging.defaults.DefaultFormat.main(DefaultFormat.java:26) ~[out/:na]

Each line has the same fields. The date, time and process id differ on every run:

  • The timestamp is ISO 8601 with milliseconds and the time zone offset, set by logging.pattern.dateformat.
  • The level is padded to five characters, then comes the process id (PID), then --- as a separator.
  • [orders] is spring.application.name; Spring Boot adds it when the property is set, and logging.include-application-name=false removes it.
  • [ main] is the thread name, right-aligned in 15 characters, then the logger name, shortened to fit 40 characters.
  • The trace and debug messages are missing: the root level is INFO.
  • The exception was printed after a blank line, with ~[out/:na] after each frame: the classpath entry the class came from and its version, unknown here because the classes are not in a jar.

When Micrometer Tracing is active, Spring Boot also adds the trace and span ids to each line through logging.pattern.correlation. Change the whole line with logging.pattern.console and logging.pattern.file; the remaining programs use short patterns so that their output stays the same from run to run.

Levels, groups and runtime changes

Four loggers in three packages of the application and one third-party library show how levels are inherited, how a group sets several at once, and how a level changes while the application runs:

Java
package logging.levels;

import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggerGroups;
import org.springframework.boot.logging.LoggingSystem;

@SpringBootApplication
public class LevelsAndGroups {

    static final Logger orders = LoggerFactory.getLogger("com.shop.orders.OrderService");
    static final Logger payments = LoggerFactory.getLogger("com.shop.payments.PaymentClient");
    static final Logger stock = LoggerFactory.getLogger("com.shop.stock.StockService");
    static final Logger library = LoggerFactory.getLogger("org.thirdparty.HttpPool");

    static void logEverything(String label) {
        System.out.println(label);
        System.out.flush();
        for (Logger log : new Logger[] {orders, payments, stock, library}) {
            log.trace("trace");
            log.debug("debug");
            log.info("info");
            log.warn("warn");
        }
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(LevelsAndGroups.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.pattern.console", "  %-5level %logger{30} - %m%n",
                "logging.level.root", "WARN",
                "logging.level.com.shop", "INFO",
                "logging.level.com.shop.orders", "DEBUG",
                "logging.group.money", "com.shop.payments,org.thirdparty",
                "logging.level.money", "TRACE"));
        try (var context = app.run(args)) {
            logEverything("1. Levels from properties:");

            LoggingSystem system = context.getBean(LoggingSystem.class);
            system.setLogLevel("com.shop", LogLevel.ERROR);
            system.setLogLevel("com.shop.orders", null);
            logEverything("2. After setLogLevel(com.shop, ERROR) and resetting com.shop.orders:");

            LoggerGroups groups = context.getBean(LoggerGroups.class);
            System.out.println("3. Logger groups:");
            groups.forEach(g -> System.out.println("  " + g.getName() + " = " + g.getMembers()));
        }
    }
}
Output
1. Levels from properties:
  DEBUG com.shop.orders.OrderService - debug
  INFO  com.shop.orders.OrderService - info
  WARN  com.shop.orders.OrderService - warn
  TRACE c.shop.payments.PaymentClient - trace
  DEBUG c.shop.payments.PaymentClient - debug
  INFO  c.shop.payments.PaymentClient - info
  WARN  c.shop.payments.PaymentClient - warn
  INFO  com.shop.stock.StockService - info
  WARN  com.shop.stock.StockService - warn
  TRACE org.thirdparty.HttpPool - trace
  DEBUG org.thirdparty.HttpPool - debug
  INFO  org.thirdparty.HttpPool - info
  WARN  org.thirdparty.HttpPool - warn
2. After setLogLevel(com.shop, ERROR) and resetting com.shop.orders:
  TRACE c.shop.payments.PaymentClient - trace
  DEBUG c.shop.payments.PaymentClient - debug
  INFO  c.shop.payments.PaymentClient - info
  WARN  c.shop.payments.PaymentClient - warn
  TRACE org.thirdparty.HttpPool - trace
  DEBUG org.thirdparty.HttpPool - debug
  INFO  org.thirdparty.HttpPool - info
  WARN  org.thirdparty.HttpPool - warn
3. Logger groups:
  money = [com.shop.payments, org.thirdparty]
  web = [org.springframework.core.codec, org.springframework.http, org.springframework.web, org.springframework.boot.actuate.endpoint.web, org.springframework.boot.web.servlet.ServletContextInitializerBeans]
  sql = [org.springframework.jdbc.core, org.hibernate.SQL, org.jooq.tools.LoggerListener]
  • OrderService logged from DEBUG up, from logging.level.com.shop.orders=DEBUG. StockService has no level of its own, so it inherited INFO from com.shop.
  • PaymentClient and org.thirdparty.HttpPool logged even TRACE. Both packages are members of the group money, and logging.level.money=TRACE set them together, although they share no package prefix.
  • After LoggingSystem.setLogLevel("com.shop", ERROR), and resetting com.shop.orders with null, both OrderService and StockService went silent: they now inherit ERROR. The payment logger kept its group level.
  • Spring Boot predefines two groups: web covers Spring's HTTP and web packages, and sql covers Spring JDBC, Hibernate's SQL logger and jOOQ. logging.level.sql=DEBUG logs every SQL statement.

The actuator loggers endpoint calls the same LoggingSystem, which is how levels are changed in production without a restart; the Actuator page shows it over HTTP. Two shortcuts also exist: --debug on the command line raises a set of core loggers (Spring Boot, Hibernate, the embedded container) to DEBUG, and --trace to TRACE.

Placeholders and the cost of disabled messages

Debug statements often stay in production code with DEBUG switched off. Whether they cost anything then depends on how the message is built. This program logs a cart whose toString is expensive, and counts how often it runs:

Java
package logging.cost;

import java.util.LinkedHashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MessageCost {

    private static final Logger log = LoggerFactory.getLogger(MessageCost.class);

    /** An argument whose toString is expensive, and counts how often it runs. */
    static class Cart {
        static int renders;
        final int[] items = new int[200];

        @Override
        public String toString() {
            renders++;
            StringBuilder sb = new StringBuilder();
            for (int item : items) {
                sb.append(item).append(',');
            }
            return "Cart[" + items.length + " items, " + sb.length() + " chars]";
        }
    }

    interface Style {
        void log(Cart cart);
    }

    static long timeNanos(Style style, Cart cart, int calls) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            long start = System.nanoTime();
            for (int i = 0; i < calls; i++) {
                style.log(cart);
            }
            best = Math.min(best, System.nanoTime() - start);
        }
        return best;
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MessageCost.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.level.logging.cost", "INFO",
                "logging.pattern.console", "  log: %level %logger{0} - %m%n"));
        try (var context = app.run(args)) {
            System.out.println("logging.level.logging.cost = "
                    + context.getEnvironment().getProperty("logging.level.logging.cost")
                    + ", debug enabled: " + log.isDebugEnabled());
            Map<String, Style> styles = new LinkedHashMap<>();
            styles.put("concatenation   ", c -> log.debug("cart " + c));
            styles.put("{} placeholder  ", c -> log.debug("cart {}", c));
            styles.put("isDebugEnabled()", c -> {
                if (log.isDebugEnabled()) {
                    log.debug("cart " + c);
                }
            });
            styles.put("atDebug() fluent", c -> log.atDebug()
                    .addArgument(() -> c.toString()).log("cart {}"));

            Cart cart = new Cart();
            int calls = 200000;
            long base = 0;
            System.out.println("Rough comparison, " + calls + " disabled debug calls, best of 3:");
            for (var entry : styles.entrySet()) {
                Cart.renders = 0;
                long nanos = timeNanos(entry.getValue(), cart, calls);
                if (base == 0) {
                    base = nanos;
                }
                long percent = nanos * 100 / base;
                System.out.println("  " + entry.getKey() + ": toString ran "
                        + Cart.renders / 3 + " times per run, "
                        + (percent < 10 ? "under 10%" : percent + "%")
                        + " of the time of concatenation");
            }
            Cart.renders = 0;
            log.info("cart {}", cart);
            System.out.flush();
            System.out.println("enabled INFO call with {}: toString ran " + Cart.renders + " time");
        }
    }
}
Output
log: INFO MessageCost - Starting MessageCost using Java 21.0.12.1 with PID 31708 (/tmp/claude-0/jv/spring/sb/SpringLogging/out started by root in /tmp/claude-0/jv)
  log: INFO MessageCost - No active profile set, falling back to 1 default profile: "default"
  log: INFO MessageCost - Started MessageCost in 0.919 seconds (process running for 1.302)
logging.level.logging.cost = INFO, debug enabled: false
Rough comparison, 200000 disabled debug calls, best of 3:
  concatenation   : toString ran 200000 times per run, 100% of the time of concatenation
  {} placeholder  : toString ran 0 times per run, under 10% of the time of concatenation
  isDebugEnabled(): toString ran 0 times per run, under 10% of the time of concatenation
  atDebug() fluent: toString ran 0 times per run, under 10% of the time of concatenation
  log: INFO MessageCost - cart Cart[200 items, 400 chars]
enabled INFO call with {}: toString ran 1 time
  • With concatenation, "cart " + c built the full string before debug was even called, so toString ran 200,000 times per run for messages that were then thrown away.
  • With the {} placeholder, SLF4J received the cart object and checked the level first; toString never ran. The same is true for the explicit isDebugEnabled() check and for SLF4J 2's fluent atDebug() API with a supplier.
  • All three took under a tenth of the concatenation's time. This is a rough comparison on a 2-core Intel Xeon at 2.1 GHz, best of 3 runs; the ratio varies between runs and machines, but the gap is always large, because the work skipped is the string building.
  • The enabled INFO call rendered the cart once, as expected.

Use placeholders everywhere. An isDebugEnabled() guard is still worth it when computing an argument is itself expensive, for example a database count, because placeholders delay only toString, not the call that produces the argument. The fluent API with a supplier, addArgument(() -> ...), delays that call too.

Logging exceptions

A payment call fails with an IOException wrapped in an UncheckedIOException. The same exception is logged in the three ways commonly found in code bases:

Java
package logging.exceptions;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExceptionLogging {

    private static final Logger log = LoggerFactory.getLogger(ExceptionLogging.class);

    static void charge(int orderId) {
        try {
            throw new IOException("connection reset");
        } catch (IOException e) {
            throw new UncheckedIOException("payment call for order " + orderId + " failed", e);
        }
    }

    static void section(String label) {
        System.out.flush();
        System.out.println(label);
        System.out.flush();
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(ExceptionLogging.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.pattern.console", "  %level %logger{0} - %m%n%wEx"));
        try (var context = app.run(args)) {
            int orderId = context.getEnvironment().getProperty("order.id", Integer.class, 1042);
            try {
                charge(orderId);
            } catch (RuntimeException e) {
                section("1. Concatenating the exception:");
                log.error("charge failed: " + e);

                section("2. Logging only the message:");
                log.error("charge failed: {}", e.getMessage());

                section("3. The exception as the last argument, after a placeholder:");
                log.error("charge failed for order {}", orderId, e);
            }
        }
    }
}
Output
1. Concatenating the exception:
  ERROR ExceptionLogging - charge failed: java.io.UncheckedIOException: payment call for order 1042 failed
2. Logging only the message:
  ERROR ExceptionLogging - charge failed: payment call for order 1042 failed
3. The exception as the last argument, after a placeholder:
  ERROR ExceptionLogging - charge failed for order 1042

java.io.UncheckedIOException: payment call for order 1042 failed
	at logging.exceptions.ExceptionLogging.charge(ExceptionLogging.java:20) ~[out/:na]
	at logging.exceptions.ExceptionLogging.main(ExceptionLogging.java:39) ~[out/:na]
Caused by: java.io.IOException: connection reset
	at logging.exceptions.ExceptionLogging.charge(ExceptionLogging.java:18) ~[out/:na]
	... 1 common frames omitted
  • Concatenation called e.toString(): the class name and message, but no stack trace and no cause. The connection reset that explains the failure is lost.
  • Logging e.getMessage() through a placeholder lost even the class name.
  • Passing the exception as the last argument, after the placeholder arguments, printed the message with the order id, the full stack trace and the Caused by: java.io.IOException: connection reset chain. SLF4J treats a final Throwable argument that has no {} of its own as the exception to print.

Log an exception once, where it is handled. Logging it at every layer that rethrows it fills the log with the same stack trace several times. ... 1 common frames omitted is Logback shortening the cause's trace where it repeats the frames already printed.

MDC: context on every line

A request id on every log line lets you find all lines of one request among thousands. SLF4J's MDC (mapped diagnostic context) holds such values per thread, and the pattern reads them with %X{key}. The program handles one request and does part of the work on two thread pools:

Java
package logging.mdc;

import java.util.Map;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@SpringBootApplication
public class MdcContext {

    private static final Logger log = LoggerFactory.getLogger(MdcContext.class);

    /** Copies the caller's MDC onto the worker thread, and clears it afterwards. */
    static class MdcTaskDecorator implements TaskDecorator {
        @Override
        public Runnable decorate(Runnable task) {
            Map<String, String> callerContext = MDC.getCopyOfContextMap();
            return () -> {
                if (callerContext != null) {
                    MDC.setContextMap(callerContext);
                }
                try {
                    task.run();
                } finally {
                    MDC.clear();
                }
            };
        }
    }

    static ThreadPoolTaskExecutor pool(String prefix, TaskDecorator decorator) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setThreadNamePrefix(prefix);
        if (decorator != null) {
            executor.setTaskDecorator(decorator);
        }
        executor.initialize();
        return executor;
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(MdcContext.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.level.logging.mdc", "INFO",
                "spring.main.log-startup-info", "false",
                "logging.pattern.console",
                "  [%-12thread] [req=%X{requestId:-none} user=%X{user:-none}] %m%n"));
        ThreadPoolTaskExecutor plain = pool("plain-", null);
        ThreadPoolTaskExecutor decorated = pool("decorated-", new MdcTaskDecorator());
        try (var context = app.run(args)) {
            log.info("context {} started", context.getId());
            MDC.put("requestId", "r-7f3a");
            MDC.put("user", "alice");
            try {
                log.info("handling GET /orders/42");
                Future<?> lost = plain.submit(() -> log.info("loading invoices"));
                lost.get();
                Future<?> kept = decorated.submit(() -> log.info("loading invoices"));
                kept.get();
                log.info("response sent");
            } finally {
                MDC.clear();
            }
            log.info("after MDC.clear()");
        } finally {
            plain.shutdown();
            decorated.shutdown();
        }
    }
}
Output
[main        ] [req=none user=none] context application started
  [main        ] [req=r-7f3a user=alice] handling GET /orders/42
  [plain-1     ] [req=none user=none] loading invoices
  [decorated-1 ] [req=r-7f3a user=alice] loading invoices
  [main        ] [req=r-7f3a user=alice] response sent
  [main        ] [req=none user=none] after MDC.clear()
  • Before MDC.put, the fields printed their defaults, none, from the :-none in the pattern.
  • On main, every line during the request carried req=r-7f3a user=alice.
  • On plain-1 the context was gone: the MDC belongs to the thread that set it, and a pool thread has its own, empty one.
  • On decorated-1 the values were back, because the TaskDecorator copied the caller's map onto the worker thread before running the task and cleared it afterwards.
  • After MDC.clear() the main thread printed none again.

Always clear the MDC in a finally block. Pool threads are reused, so a value left behind appears on the next, unrelated request. In a web application, a servlet filter is the usual place to put and clear the request id. When Micrometer Tracing is on the classpath, it puts traceId and spanId into the MDC for you; the observability page shows that. The @Async page applies the same decorator to @Async methods.

Structured JSON logging

Log platforms such as Elasticsearch, Loki or Graylog search fields, not text. Since Spring Boot 3.4, one property switches the console or file output to JSON, in one of three formats: ecs (Elastic Common Schema), logstash and gelf. The program logs one message with an MDC value and an SLF4J key-value pair in two formats:

Java
package logging.structured;

import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class StructuredLogging {

    private static final Logger log = LoggerFactory.getLogger(StructuredLogging.class);

    static void run(String format) {
        System.out.println("logging.structured.format.console=" + format);
        System.out.flush();
        SpringApplication app = new SpringApplication(StructuredLogging.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "spring.main.log-startup-info", "false",
                "spring.application.name", "orders",
                "logging.level.root", "WARN",
                "logging.level.logging.structured", "INFO",
                "logging.structured.format.console", format,
                "logging.structured.json.exclude", "@timestamp,timestamp,process.pid"));
        try (var context = app.run()) {
            MDC.put("orderId", "1042");
            log.atInfo().addKeyValue("items", 3).log("order placed in {}", context.getId());
            MDC.clear();
        }
    }

    public static void main(String[] args) {
        run("ecs");
        run("logstash");
    }
}
Output
logging.structured.format.console=ecs
{"log":{"level":"INFO","logger":"logging.structured.StructuredLogging"},"process":{"thread":{"name":"main"}},"service":{"name":"orders","node":{}},"message":"order placed in orders","orderId":"1042","items":3,"ecs":{"version":"8.11"}}
logging.structured.format.console=logstash
{"@version":"1","message":"order placed in orders","logger_name":"logging.structured.StructuredLogging","thread_name":"main","level":"INFO","level_value":20000,"orderId":"1042","items":3}
  • Each event is one line of JSON. The MDC value orderId and the key-value pair items became top-level fields; items kept its type, the number 3.
  • ECS nests fields (log.level, process.thread.name), takes service.name from spring.application.name and adds ecs.version. Logstash uses flat names such as logger_name and level_value.
  • The timestamps and the process id were removed with logging.structured.json.exclude, only so that the output is the same on every run. Keep them in a real application.

logging.structured.json.rename, add and a StructuredLoggingJsonMembersCustomizer bean adjust the fields further, and logging.structured.format.file applies a format to the log file only. A common setup is human-readable text on the console during development and JSON in containers, switched by a profile.

Files and logback-spring.xml

Properties cover levels, patterns and a single log file. For several appenders or different behaviour per environment, Spring Boot reads a Logback file named logback-spring.xml. This program runs the same configuration with the dev and prod profiles:

Java
package logging.xml;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LogbackSpringXml {

    private static final Logger log = LoggerFactory.getLogger("com.shop.OrderService");

    static final String CONFIG = """
            <configuration>
              <springProperty scope="context" name="app" source="spring.application.name"/>

              <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
                <encoder><pattern>  console: [${app}] %-5level %m%n</pattern></encoder>
              </appender>

              <springProfile name="dev">
                <logger name="com.shop" level="DEBUG"/>
                <root level="WARN"><appender-ref ref="CONSOLE"/></root>
              </springProfile>

              <springProfile name="prod">
                <appender name="FILE" class="ch.qos.logback.core.FileAppender">
                  <file>${LOG_FILE}</file>
                  <encoder><pattern>  file: [${app}] %-5level %m%n</pattern></encoder>
                </appender>
                <logger name="com.shop" level="INFO"/>
                <root level="WARN">
                  <appender-ref ref="CONSOLE"/>
                  <appender-ref ref="FILE"/>
                </root>
              </springProfile>
            </configuration>
            """;

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("logging");
        Path xml = Files.writeString(dir.resolve("logback-spring.xml"), CONFIG);
        Path logFile = dir.resolve("orders.log");

        for (String profile : new String[] {"dev", "prod"}) {
            System.out.println("spring.profiles.active=" + profile);
            System.out.flush();
            SpringApplication app = new SpringApplication(LogbackSpringXml.class);
            app.setDefaultProperties(Map.of(
                    "spring.main.banner-mode", "off",
                    "spring.application.name", "orders",
                    "spring.profiles.active", profile,
                    "logging.config", xml.toUri().toString(),
                    "logging.file.name", logFile.toString()));
            try (var context = app.run(args)) {
                log.debug("price lookup took {} ms", 12);
                log.info("order {} placed", 1042);
                log.warn("stock low for {}", context.getEnvironment()
                        .getProperty("demo.sku", "BOOK-7"));
            }
            System.out.flush();
        }
        System.out.println("Contents of the log file:");
        Files.readAllLines(logFile).forEach(System.out::println);
    }
}
Output
spring.profiles.active=dev
console: [orders] DEBUG price lookup took 12 ms
console: [orders] INFO  order 1042 placed
console: [orders] WARN  stock low for BOOK-7
spring.profiles.active=prod
console: [orders] INFO  order 1042 placed
console: [orders] WARN  stock low for BOOK-7
Contents of the log file:
file: [orders] INFO  order 1042 placed
file: [orders] WARN  stock low for BOOK-7
  • With dev, the <springProfile name="dev"> block set com.shop to DEBUG, so the price lookup appeared, and only the console appender was attached.
  • With prod, the debug line was gone and each message went to both the console and the file. The file's own pattern, file:, shows which appender wrote it.
  • [orders] came from <springProperty>, which copied spring.application.name into the Logback context.
  • ${LOG_FILE} was filled from logging.file.name; Spring Boot passes several logging.* properties to Logback as variables like this.

The -spring suffix matters: Spring Boot loads a plain logback.xml too, but Logback reads it before Spring starts, so <springProfile> and <springProperty> do not work in it. The program points logging.config at the file because it writes it at runtime; in an application, put logback-spring.xml in src/main/resources. Without any XML, logging.file.name=app.log gives a rolling file that rolls daily or at 10 MB and keeps at most 7 archive files, adjustable through logging.logback.rollingpolicy.*.

Switching to Log4j 2

Spring Boot also supports Log4j 2 as the backend. The switch is made in the build: exclude spring-boot-starter-logging, which brings Logback and the bridges into SLF4J, and add spring-boot-starter-log4j2, which brings log4j-core, log4j-slf4j2-impl (SLF4J calls go to Log4j) and log4j-jul. Both libraries must not be on the classpath together: log4j-to-slf4j sends Log4j calls to SLF4J and log4j-slf4j2-impl sends SLF4J calls to Log4j.

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

This program ran with that classpath: Spring Boot 4.1.2 with Log4j 2.25.5, and no Logback jars. It writes a log4j2-spring.xml with a Spring profile block, then logs through three different APIs:

Java
package logging.log4j2;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;

@SpringBootApplication
public class Log4j2Logging {

    private static final Logger log = LoggerFactory.getLogger("com.shop.OrderService");

    static final String CONFIG = """
            <Configuration>
              <Appenders>
                <Console name="CONSOLE" target="SYSTEM_OUT">
                  <PatternLayout pattern="  log4j2: [${spring:spring.application.name}] \
            %-5level %c{1} - %m%n"/>
                </Console>
              </Appenders>
              <Loggers>
                <SpringProfile name="dev">
                  <Logger name="com.shop" level="DEBUG"/>
                </SpringProfile>
                <Root level="WARN"><AppenderRef ref="CONSOLE"/></Root>
              </Loggers>
            </Configuration>
            """;

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("logging");
        Path xml = Files.writeString(dir.resolve("log4j2-spring.xml"), CONFIG);

        SpringApplication app = new SpringApplication(Log4j2Logging.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "spring.application.name", "orders",
                "spring.profiles.active", "dev",
                "logging.config", xml.toUri().toString()));
        try (var context = app.run(args)) {
            LoggingSystem system = context.getBean(LoggingSystem.class);
            System.out.println("LoggingSystem: " + system.getClass().getSimpleName());
            System.out.println("SLF4J binding: "
                    + LoggerFactory.getILoggerFactory().getClass().getName());
            System.out.flush();

            log.debug("price lookup took {} ms", 12);                     // SLF4J API
            log.info("order {} placed", 1042);
            LogManager.getLogger("com.shop.Billing").info("invoice {} sent", 77); // Log4j API
            java.util.logging.Logger.getLogger("com.shop.Legacy")   // JUL: name clash with SLF4J
                    .info("message from java.util.logging");

            system.setLogLevel("com.shop", LogLevel.WARN);
            log.info("this info line is now filtered out");
            log.warn("stock low for {}", "BOOK-7");
        }
        Files.delete(xml);
        Files.delete(dir);
    }
}
Output
LoggingSystem: Log4J2LoggingSystem
SLF4J binding: org.apache.logging.slf4j.Log4jLoggerFactory
  log4j2: [orders] DEBUG OrderService - price lookup took 12 ms
  log4j2: [orders] INFO  OrderService - order 1042 placed
  log4j2: [orders] INFO  Billing - invoice 77 sent
  log4j2: [orders] INFO  Legacy - message from java.util.logging
  log4j2: [orders] WARN  OrderService - stock low for BOOK-7
  • Spring Boot detected Log4j on the classpath and chose Log4J2LoggingSystem, and SLF4J was bound to Log4j's Log4jLoggerFactory. The application code still uses the SLF4J API and did not change.
  • The DEBUG line appeared because <SpringProfile name="dev"> set com.shop to DEBUG. Like <springProfile> in Logback, it only works in the -spring file that Spring Boot loads.
  • [orders] came from the ${spring:spring.application.name} lookup, which reads any property from the Spring Environment. It is Log4j's counterpart of <springProperty>.
  • A message from the Log4j API and one from java.util.logging went to the same appender. The JUL message was routed into Log4j through log4j-jul, which the starter brings.
  • After setLogLevel("com.shop", LogLevel.WARN) the info line was filtered out and the warning printed. The LoggingSystem bean and the actuator loggers endpoint work the same with either backend, as do the logging.* properties.

Logback is the default and needs no change to the build. The logging.logback.rollingpolicy.* properties are Logback-only; with Log4j 2, file rolling is configured in log4j2-spring.xml. Choose Log4j 2 when the organisation already standardises on its configuration, or for its asynchronous loggers, which need the LMAX Disruptor library as an extra dependency.

Choosing a logging setup

Logging needs and the feature that fits each
NeedUse
More or less detail from a packagelogging.level.<package>
Several unrelated packages at one levellogging.group.<name>, or the built-in web and sql groups
Changing a level without a restartThe actuator loggers endpoint, or LoggingSystem.setLogLevel
Cheap debug statements{} placeholders; atDebug() with a supplier for expensive arguments
ExceptionsThe exception as the last argument, logged once where it is handled
Request ids and user ids on each lineMDC with %X{key}, a TaskDecorator for thread pools
Logs for Elasticsearch, Loki or Grayloglogging.structured.format.console=ecs, logstash or gelf
Different appenders per environmentlogback-spring.xml with <springProfile>
Log4j 2 instead of LogbackExclude spring-boot-starter-logging, add spring-boot-starter-log4j2 and log4j2-spring.xml
A log file with rotationlogging.file.name and logging.logback.rollingpolicy.*

Most applications need nothing beyond properties: levels per package, one pattern or a structured format, and a file only where the platform does not collect the console. The profiles page shows how to switch these settings per environment, and configuration properties explains where the logging.* values can come from.