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(...)
Spring Boot picks both for you. spring-boot-starter-logging
- SLF4J: the facade your code uses, through
.LoggerFactory.getLogger(...) - Logback: the default backend.
- Bridges:
andjul-to-slf4j redirectlog4j-to-slf4j 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.java.util.logging
On top of the backend, Spring Boot adds its LoggingSystemlogging.*logging.level.com.example=DEBUGapplication.properties
| Level | Use for | On by default |
|---|---|---|
TRACE | Very fine detail: each loop step, each SQL parameter | No |
DEBUG | Diagnostic detail for developers | No |
INFO | Normal milestones: started, order placed | Yes |
WARN | Something unexpected that the application handled | Yes |
ERROR | A failure that needs attention | Yes |
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.OrderServicecom.shop.orderscom.shop
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:
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"));
}
}
}
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.--- is[orders] ; Spring Boot adds it when the property is set, andspring.application.name removes it.logging.include-application-name=false is the thread name, right-aligned in 15 characters, then the logger name, shortened to fit 40 characters.[ main]- The
andtrace messages are missing: the root level isdebug .INFO - The exception was printed after a blank line, with
after each frame: the classpath entry the class came from and its version, unknown here because the classes are not in a jar.~[out/:na]
When Micrometer Tracing is active, Spring Boot also adds the trace and span ids to each line through logging.pattern.correlationlogging.pattern.consolelogging.pattern.file
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:
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()));
}
}
}
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]
logged fromOrderService up, fromDEBUG .logging.level.com.shop.orders=DEBUG has no level of its own, so it inheritedStockService fromINFO .com.shop andPaymentClient logged evenorg.thirdparty.HttpPool . Both packages are members of the groupTRACE , andmoney set them together, although they share no package prefix.logging.level.money=TRACE- After
, and resettingLoggingSystem.setLogLevel("com.shop", ERROR) withcom.shop.orders , bothnull andOrderService went silent: they now inheritStockService . The payment logger kept its group level.ERROR - Spring Boot predefines two groups:
covers Spring's HTTP and web packages, andweb covers Spring JDBC, Hibernate's SQL logger and jOOQ.sql logs every SQL statement.logging.level.sql=DEBUG
The actuator loggersLoggingSystem--debugDEBUG--traceTRACE
Placeholders and the cost of disabled messages
Debug statements often stay in production code with DEBUGtoString
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");
}
}
}
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,
built the full string before"cart " + c was even called, sodebug ran 200,000 times per run for messages that were then thrown away.toString - With the
placeholder, SLF4J received the cart object and checked the level first;{} never ran. The same is true for the explicittoString check and for SLF4J 2's fluentisDebugEnabled() API with a supplier.atDebug() - 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
call rendered the cart once, as expected.INFO
Use placeholders everywhere. An isDebugEnabled()toStringaddArgument(() -> ...)
Logging exceptions
A payment call fails with an IOExceptionUncheckedIOException
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);
}
}
}
}
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
: the class name and message, but no stack trace and no cause. Thee.toString() that explains the failure is lost.connection reset - Logging
through a placeholder lost even the class name.e.getMessage() - Passing the exception as the last argument, after the placeholder arguments, printed the message with the order id, the full stack trace and the
chain. SLF4J treats a finalCaused by: java.io.IOException: connection reset argument that has noThrowable 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
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}
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();
}
}
}
[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
, the fields printed their defaults,MDC.put , from thenone in the pattern.:-none - On
, every line during the request carriedmain .req=r-7f3a user=alice - On
the context was gone: the MDC belongs to the thread that set it, and a pool thread has its own, empty one.plain-1 - On
the values were back, because thedecorated-1 copied the caller's map onto the worker thread before running the task and cleared it afterwards.TaskDecorator - After
the main thread printedMDC.clear() again.none
Always clear the MDC in a finallytraceIdspanId@Async
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: ecslogstashgelf
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");
}
}
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
and the key-value pairorderId became top-level fields;items kept its type, the number 3.items - ECS nests fields (
,log.level ), takesprocess.thread.name fromservice.name and addsspring.application.name . Logstash uses flat names such asecs.version andlogger_name .level_value - The timestamps and the process id were removed with
, only so that the output is the same on every run. Keep them in a real application.logging.structured.json.exclude
logging.structured.json.renameaddStructuredLoggingJsonMembersCustomizerlogging.structured.format.file
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.xmldevprod
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);
}
}
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
, thedev block set<springProfile name="dev"> tocom.shop , so the price lookup appeared, and only the console appender was attached.DEBUG - With
, the debug line was gone and each message went to both the console and the file. The file's own pattern,prod , shows which appender wrote it.file: came from[orders] , which copied<springProperty> into the Logback context.spring.application.name was filled from${LOG_FILE} ; Spring Boot passes severallogging.file.name properties to Logback as variables like this.logging.*
The -springlogback.xml<springProfile><springProperty>logging.configlogback-spring.xmlsrc/main/resourceslogging.file.name=app.loglogging.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-loggingspring-boot-starter-log4j2log4j-corelog4j-slf4j2-impllog4j-jullog4j-to-slf4jlog4j-slf4j2-impl
<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
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);
}
}
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
, and SLF4J was bound to Log4j'sLog4J2LoggingSystem . The application code still uses the SLF4J API and did not change.Log4jLoggerFactory - The
line appeared becauseDEBUG set<SpringProfile name="dev"> tocom.shop . LikeDEBUG in Logback, it only works in the<springProfile> file that Spring Boot loads.-spring came from the[orders] lookup, which reads any property from the Spring${spring:spring.application.name} . It is Log4j's counterpart ofEnvironment .<springProperty>- A message from the Log4j API and one from
went to the same appender. The JUL message was routed into Log4j throughjava.util.logging , which the starter brings.log4j-jul - After
the info line was filtered out and the warning printed. ThesetLogLevel("com.shop", LogLevel.WARN) bean and the actuatorLoggingSystem endpoint work the same with either backend, as do theloggers properties.logging.*
Logback is the default and needs no change to the build. The logging.logback.rollingpolicy.*log4j2-spring.xml
Choosing a logging setup
| Need | Use |
|---|---|
| More or less detail from a package | logging.level.<package> |
| Several unrelated packages at one level | logging.group.<name>websql |
| Changing a level without a restart | The actuator loggersLoggingSystem.setLogLevel |
| Cheap debug statements | {}atDebug() |
| Exceptions | The exception as the last argument, logged once where it is handled |
| Request ids and user ids on each line | MDC with %X{key}TaskDecorator |
| Logs for Elasticsearch, Loki or Graylog | logging.structured.format.console=ecslogstashgelf |
| Different appenders per environment | logback-spring.xml<springProfile> |
| Log4j 2 instead of Logback | Exclude spring-boot-starter-loggingspring-boot-starter-log4j2log4j2-spring.xml |
| A log file with rotation | logging.file.namelogging.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 logging.*