00:00

Logging in Spring Boot

Last updated:

Logging in Spring Boot works out of the box: every application starts with SLF4J as the logging API, Logback as the logging engine, a readable console format and sensible log levels. Good logs are still something you design. You decide what to log at which level, where the logs go, how they are formatted for your log platform, and how to follow one request through thousands of lines.

This tutorial explains how Spring Boot's logging is put together, how to set levels per package and with log groups, how to write log files with rotation, how to switch to JSON structured logs for tools such as Elasticsearch or Loki, how to add a correlation ID to every line with MDC, and how to change log levels at runtime without a restart.

1. How Logging in Spring Boot Works

Logging in Java has two layers, and Spring Boot sets up both:

  • The logging API is what your code calls. Spring Boot uses SLF4J (Simple Logging Facade for Java), a thin interface with methods such as log.info(...).
  • The logging backend decides what happens to each message: which messages are kept, how they are formatted and where they are written. The default backend is Logback; Log4j2 is the main alternative.

Every starter brings spring-boot-starter-logging, which contains Logback plus bridges that route other logging APIs (java.util.logging, Log4j API, Apache Commons Logging) into SLF4J. So libraries that use different APIs all end up in the same log output. Spring Boot's LoggingSystem then configures the backend from your logging.* properties, very early during startup.

How a log message travels in a Spring Boot applicationYour code and libraries call SLF4J or other logging APIs, which are bridged into SLF4J. Logback receives each event, checks the logger's level and drops messages below it, adds context such as the thread name and MDC values, formats the event as plain text or JSON, and writes it to the console, a rotating file, or both. Spring Boot configures Logback from logging properties at startup. Your code and libraries log.info(...) SLF4J API (other APIs are bridged in) Logback level check, MDC, format: text or JSON Console (stdout for containers) Rotating log file logging.file.name Spring Boot configures Logback from logging.* properties at startup
Your code talks to SLF4J; Logback filters by level, formats the event and writes it to the console or files.

2. Writing Log Messages with SLF4J

Create one logger per class and use placeholders ({}) instead of string concatenation. The message is only built if the level is enabled, and the last argument can be an exception, which prints its stack trace.

PaymentService.java (logging basics)
private static final Logger log = LoggerFactory.getLogger(PaymentService.class);

public void charge(String orderId, BigDecimal amount) {
    log.debug("Charging order {} amount {}", orderId, amount);          // details for developers
    try {
        gateway.charge(orderId, amount);
        log.info("Payment captured for order {}", orderId);             // business event
    } catch (GatewayTimeoutException ex) {
        log.warn("Payment gateway timed out for order {}, will retry", orderId);
        throw ex;
    } catch (RuntimeException ex) {
        log.error("Payment failed for order {}", orderId, ex);          // exception last: stack trace
        throw ex;
    }
}

SLF4J 2 also has a fluent API that can attach key-value pairs, which structured JSON logging (section 6) turns into separate fields:

Fluent logging
log.atInfo()
   .setMessage("Payment captured")
   .addKeyValue("orderId", orderId)
   .addKeyValue("amount", amount)
   .log();
Lombok tip: @Slf4j on a class generates the same log field; see Spring Boot with Lombok.

3. Log Levels and How to Set Them

LevelUse forExample
ERRORA failure that needs attentionPayment failed, message could not be processed
WARNSomething unexpected the application recovered fromRetrying a timed-out call, falling back to a default
INFOImportant business and lifecycle eventsOrder placed, application started
DEBUGDetails useful when investigating a problemInput values, decisions taken
TRACEVery detailed, step-by-step informationEvery SQL parameter, every loop iteration

The root level is INFO, so DEBUG and TRACE messages are dropped unless you lower the level. Set levels per package with logging.level.<package>:

application.properties
logging.level.root=INFO
logging.level.com.javabytechie.shop=DEBUG
logging.level.org.springframework.web=WARN

Like any property, a level can also come from an environment variable (LOGGING_LEVEL_COM_JAVABYTECHIE_SHOP=DEBUG) or a command-line argument. Starting with --debug switches on debug output for a selection of core loggers, such as the embedded container and Hibernate, without making your whole application verbose.

3.1 Log Groups

A log group gives several packages one name, so you can change them together. Spring Boot predefines two: web (Spring MVC and related packages) and sql (Spring JDBC and Hibernate SQL logging).

application.properties
logging.group.checkout=com.javabytechie.shop.order,com.javabytechie.shop.payment
logging.level.checkout=DEBUG
logging.level.sql=DEBUG

3.2 Levels per Environment

Put noisy levels in a development profile file such as application-dev.properties, so production stays at INFO. See Spring Boot profiles.

4. Reading the Default Log Format

Console
2026-12-04T10:15:42.318+05:30  INFO 48213 --- [shop] [nio-8080-exec-3] c.j.shop.order.OrderService              : Order ORD-1001 placed for 2 items
PartMeaning
2026-12-04T10:15:42.318+05:30Date and time with millisecond precision and time zone offset
INFOLog level
48213Process ID
---Separator before the actual log content
[shop]Application name from spring.application.name (hide it with logging.include-application-name=false)
[nio-8080-exec-3]Thread name
c.j.shop.order.OrderServiceLogger name, usually the class, with packages shortened
Text after :The message

When tracing is enabled through Micrometer Tracing, a correlation section with the trace and span IDs is added automatically. You can change the patterns with logging.pattern.console and logging.pattern.file, but for machine processing JSON is the better choice.

5. Logging to a File with Rotation

By default Spring Boot logs only to the console, which is what containers and Kubernetes expect. To also write a file, set one property:

application.properties
logging.file.name=logs/shop.log
logging.logback.rollingpolicy.max-file-size=20MB
logging.logback.rollingpolicy.max-history=14
logging.logback.rollingpolicy.total-size-cap=1GB
PropertyDefaultMeaning
logging.file.namenoneLog file path; wins over logging.file.path
logging.file.pathnoneDirectory for a file named spring.log
logging.logback.rollingpolicy.max-file-size10MBSize at which the file is archived
logging.logback.rollingpolicy.max-history7Number of archived files to keep
logging.logback.rollingpolicy.total-size-capno limitMaximum total size of the archives
Version note: since Spring Boot 4.0, Logback writes log files in UTF-8 by default, matching Log4j2, and the console uses the console's own charset when it is available.

6. Structured JSON Logging

Structured logging writes each event as a JSON object instead of a line of text. Log platforms can then search by field (level, logger, order ID) without fragile text parsing. Spring Boot supports three formats out of the box: Elastic Common Schema (ecs), Graylog Extended Log Format (gelf) and Logstash (logstash).

application.properties
logging.structured.format.console=ecs
Console (one line per event, formatted here for reading)
{
  "@timestamp": "2026-12-04T04:45:42.318Z",
  "log": { "level": "INFO", "logger": "com.javabytechie.shop.order.OrderService" },
  "process": { "pid": 48213, "thread": { "name": "http-nio-8080-exec-3" } },
  "service": { "name": "shop" },
  "message": "Order ORD-1001 placed",
  "orderId": "ORD-1001",
  "correlationId": "c0a8-7f3e",
  "ecs": { "version": "8.11" }
}

Values in the MDC and key-value pairs from the fluent API become fields of the JSON object. The exact set of fields depends on the format and version, so check your output once before building dashboards. You can shape the JSON with properties:

application.properties
logging.structured.json.exclude=ecs.version
logging.structured.json.add.environment=production
logging.structured.ecs.service.version=1.4.0

Use logging.structured.format.file for JSON files. A common setup is readable text in development and JSON in production, chosen per profile.

7. Correlation IDs with MDC

When many requests run at once, their log lines interleave. A correlation ID is a value added to every line of one request so you can filter them. SLF4J's MDC (Mapped Diagnostic Context) holds such values for the current thread, and the backend adds them to each log event.

A servlet filter is the right place to set it, because it runs once at the start of each request and can clean up at the end. The filter mechanics are explained in filters vs interceptors.

CorrelationIdFilter.java
package com.javabytechie.shop.web;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorrelationIdFilter extends OncePerRequestFilter {

    static final String HEADER = "X-Correlation-Id";
    static final String MDC_KEY = "correlationId";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String incoming = request.getHeader(HEADER);
        String correlationId = (incoming != null && incoming.matches("[A-Za-z0-9-]{1,64}"))
                ? incoming
                : UUID.randomUUID().toString();
        MDC.put(MDC_KEY, correlationId);
        response.setHeader(HEADER, correlationId);
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.remove(MDC_KEY);   // threads are reused; never leave values behind
        }
    }
}

To show the value in plain-text logs, add it to the pattern; JSON formats include MDC values automatically:

application.properties
logging.pattern.correlation=[%X{correlationId:-}] 

The incoming header is validated before use so a client cannot inject arbitrary text into your logs. If you use Micrometer Tracing, trace and span IDs are put into the MDC for you and propagated between services; see distributed tracing.

8. A Complete Example: Logging an Order Service

8.1 The Service

OrderService.java
package com.javabytechie.shop.order;

import java.math.BigDecimal;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

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

    public String place(String customerId, List<String> skus, BigDecimal total) {
        log.debug("Placing order for customer {} with items {}", customerId, skus);
        if (skus.isEmpty()) {
            log.warn("Rejected empty order from customer {}", customerId);
            throw new IllegalArgumentException("An order needs at least one item");
        }
        String orderId = "ORD-" + (1000 + Math.abs(customerId.hashCode() % 9000));
        log.atInfo()
           .setMessage("Order placed")
           .addKeyValue("orderId", orderId)
           .addKeyValue("itemCount", skus.size())
           .addKeyValue("total", total)
           .log();
        return orderId;
    }
}

8.2 The Controller

OrderController.java
package com.javabytechie.shop.order;

import java.math.BigDecimal;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private final OrderService orders;

    public OrderController(OrderService orders) {
        this.orders = orders;
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public OrderPlaced place(@RequestBody PlaceOrder request) {
        return new OrderPlaced(orders.place(request.customerId(), request.skus(), request.total()));
    }

    public record PlaceOrder(String customerId, List<String> skus, BigDecimal total) {
    }

    public record OrderPlaced(String orderId) {
    }
}

8.3 Configuration per Profile

application.properties
spring.application.name=shop
logging.level.com.javabytechie.shop=INFO
logging.pattern.correlation=[%X{correlationId:-}] 
application-dev.properties
logging.level.com.javabytechie.shop=DEBUG
application-prod.properties
logging.structured.format.console=ecs

8.4 Output in Development

Terminal
curl -s -X POST localhost:8080/api/orders -H "Content-Type: application/json" \
     -H "X-Correlation-Id: checkout-42" \
     -d '{"customerId":"CUST-7","skus":["KB-100","MS-200"],"total":104.98}'
Console (dev profile)
2026-12-04T10:15:42.301+05:30 DEBUG 48213 --- [shop] [nio-8080-exec-3] [checkout-42] c.j.shop.order.OrderService : Placing order for customer CUST-7 with items [KB-100, MS-200]
2026-12-04T10:15:42.318+05:30  INFO 48213 --- [shop] [nio-8080-exec-3] [checkout-42] c.j.shop.order.OrderService : Order placed

In the text format the key-value pairs of the fluent call are not shown, but in the prod profile's JSON output they appear as orderId, itemCount and total fields, next to correlationId. The ID received in the header is reused, so the same request can be followed across services. Column widths are shortened here.

9. Changing Log Levels at Runtime

With Actuator, the loggers endpoint shows and changes levels while the application runs, which is ideal for switching on DEBUG briefly in production:

application.properties
management.endpoints.web.exposure.include=health,loggers
Terminal
curl -s localhost:8080/actuator/loggers/com.javabytechie.shop.order
curl -s -X POST localhost:8080/actuator/loggers/com.javabytechie.shop.order \
     -H "Content-Type: application/json" -d '{"configuredLevel":"DEBUG"}'
# reset to the configured default
curl -s -X POST localhost:8080/actuator/loggers/com.javabytechie.shop.order \
     -H "Content-Type: application/json" -d '{"configuredLevel":null}'

The change applies only to that instance and is lost on restart. Protect the endpoint with Spring Security; see Spring Boot Actuator.

10. Custom Logback Configuration and Log4j2

10.1 logback-spring.xml

When properties are not enough, for example to send one logger to a separate file, add logback-spring.xml to src/main/resources. Use the -spring name rather than logback.xml: Spring Boot then controls initialization and adds extensions such as <springProfile>.

logback-spring.xml
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>

    <springProfile name="dev">
        <logger name="com.javabytechie.shop" level="DEBUG"/>
    </springProfile>

    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
    </root>
</configuration>

Including Spring Boot's defaults.xml and console-appender.xml keeps the standard patterns and colors. Once you provide this file, the file-related logging.* properties only work if your configuration includes the matching Spring Boot appenders.

10.2 Switching to Log4j2

Exclude the default logging starter and add the Log4j2 one. Your code does not change, because it uses the SLF4J API:

pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webmvc</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>

11. Common Logging Mistakes

  • String concatenation: log.debug("Order " + order) builds the string even when DEBUG is off. Use {} placeholders.
  • Logging and rethrowing at every layer: the same stack trace appears five times. Log an exception once, where it is handled.
  • Losing the stack trace: log.error("Failed: " + ex.getMessage()) drops the cause. Pass the exception as the last argument.
  • Logging secrets and personal data: tokens, passwords, card numbers and full request bodies do not belong in logs; see managing secrets.
  • Leaving MDC values behind: without MDC.remove in a finally block, the next request on the same thread inherits the old value.
  • System.out.println: it bypasses levels, formats and the log pipeline entirely.

12. Best Practices

  • Log to the console in containers and let the platform collect and ship the output.
  • Use JSON structured logging in production and readable text in development.
  • Keep production at INFO and raise levels temporarily through the loggers endpoint.
  • Add a correlation ID to every request with a filter and MDC, or with Micrometer Tracing.
  • Log business events at INFO with stable keys such as orderId, so they can be searched and counted.
  • Log each exception once, with its stack trace, at the place it is handled.
  • Cap file growth with rotation properties whenever you write log files.

13. Summary

Logging in Spring Boot combines the SLF4J API with Logback, configured from logging.* properties. Set levels per package or with log groups, write rotating files with logging.file.name when you need them, and switch to JSON with logging.structured.format.console so log platforms can search by field. Add a correlation ID through a filter and MDC, attach business data with SLF4J's fluent key-value API, and change levels at runtime with the Actuator loggers endpoint. Keep messages meaningful, log exceptions once, and never log secrets, and your logs will answer questions instead of creating them.

14. References