Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 66 ยท Auto-Configuration and Configuration

Logging

Configure Spring Boot logging with SLF4J and Logback: levels, groups, patterns, JSON logs, MDC correlation IDs, and the pitfalls of string concatenation and leaked secrets.

When something goes wrong in production, logs are usually all you have. Good logging answers three questions quickly: what happened, to which request or user, and in what order. Bad logging buries the answer in noise, costs CPU on every request, or, worst of all, writes passwords into a file that ten teams can read.

Spring Boot gives you a working logging setup out of the box. This lesson explains what that setup is made of, how to control levels and output format with a few properties, how to put a correlation ID on every line with MDC, and which mistakes to avoid. Boot configuration is read-only here; two runnable stand-ins rebuild a level-aware logger on top of System.Logger and a request-scoped MDC with JSON output.

The pieces: SLF4J, Logback and Boot

Java has many logging libraries, so applications talk to a facade and let a backend do the work.

Three layers

SLF4J The API your code calls.
Logback The default backend that formats and writes.
Bridges Route Log4j, JUL and commons-logging into SLF4J.

Your code never imports Logback.

1 / 2

spring-boot-starter already pulls in spring-boot-starter-logging, which brings SLF4J, Logback and the bridges. You use it like this:

Java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class OrderService {

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

    public void place(long orderId, String customer) {
        log.info("Placing order {} for customer {}", orderId, customer);
        try {
            // ...
        } catch (PaymentException e) {
            log.error("Payment failed for order {}", orderId, e);
            throw e;
        }
    }
}

Name the logger after the class: its name (com.shop.order.OrderService) is what level configuration and pattern output refer to. Notice the {} placeholders and the exception as the last argument, which makes SLF4J print the full stack trace.

Levels

Each message has a level, from most to least detailed: TRACE, DEBUG, INFO, WARN, ERROR. A logger prints a message only when the message level is at least the logger's configured level. Boot's default for everything is INFO.

Level Use it for
ERROR The operation failed and someone should look at it
WARN Something unexpected happened, but the app recovered
INFO Important business or lifecycle events: start, stop, order placed
DEBUG Detail for developers while diagnosing
TRACE Very fine detail, such as every step in a loop

Levels are inherited through the package hierarchy: a logger named com.shop.order.OrderService uses the nearest configured ancestor (com.shop.order, then com.shop, and finally root).

YAML
logging:
  level:
    root: INFO
    com.shop: DEBUG
    com.shop.payment: WARN
    org.hibernate.SQL: DEBUG

You can also set levels for a quick experiment without editing files: --logging.level.com.shop.order=TRACE on the command line, or --debug to switch on Boot's own diagnostic output (the auto-configuration report from How Auto-Configuration Works).

Log groups

A group gives one name to several loggers so that you can change them together. Boot predefines web (Spring MVC internals) and sql (SQL statements), and you can add your own:

YAML
logging:
  group:
    persistence: org.hibernate.SQL, org.springframework.jdbc.core
  level:
    persistence: DEBUG
    web: DEBUG

Seeing how levels resolve

The first TryIt is a small logger built on the JDK's own System.Logger interface, which exists for the same reason as SLF4J: a facade with pluggable backends. Our backend resolves levels through the package hierarchy, formats lines with a fixed pattern, and a thin wrapper adds SLF4J-style {} placeholders. It also demonstrates why parameters beat string concatenation.

Java A level-aware logger on System.Logger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: the facade-and-backend split (System.Logger here, SLF4J plus Logback in Boot), inheritance of levels through the logger name, and skipping the formatting work when the level is off. What is the stand-in: Logback also does appenders, rolling files, asynchronous writing, markers and lazy {} formatting with far more care.

Patterns, files and JSON

Boot's console pattern is readable by humans: time, level, process id, thread, logger and message. Change it, or write to a file, with properties:

YAML
logging:
  pattern:
    console: "%d{HH:mm:ss.SSS} %-5level [%X{requestId}] %logger{36} - %msg%n"
  file:
    name: logs/shop.log
  logback:
    rollingpolicy:
      max-file-size: 20MB
      max-history: 14

Plain text is fine on a laptop, but log platforms such as Elasticsearch, Loki or a cloud logging service parse structured lines much more reliably. Boot can write JSON itself:

YAML
logging:
  structured:
    format:
      console: ecs        # also: logstash, gelf

Every line becomes one JSON object with timestamp, level, logger, message, stack trace and the MDC values. In containers, log to the console (standard output) and let the platform collect it; managing log files inside a container is the platform's job, not yours.

MDC and correlation IDs

When twenty requests run at once, their log lines interleave. Which Payment failed belongs to which user? The MDC (Mapped Diagnostic Context) is a per-thread map of values that the logging backend adds to every line. You set a request ID once, in a filter at the start of the request, and every log call on that thread carries it automatically:

Java
@Component
public class RequestIdFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String id = Optional.ofNullable(request.getHeader("X-Request-Id"))
                .orElseGet(() -> UUID.randomUUID().toString());
        MDC.put("requestId", id);
        response.setHeader("X-Request-Id", id);
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.clear();            // threads are reused: always clean up
        }
    }
}

Reference the value in the pattern with %X{requestId}, or find it as a field in JSON output. When your service calls other services, forward the same ID in a header so one search finds the whole journey. If you use Micrometer Tracing (see Observability), Boot adds trace and span IDs to the MDC for you, which is the standard form of this idea.

Two traps: the MDC is thread-local, so a task submitted to another executor starts with an empty MDC unless you copy it; and a pooled thread that is not cleared leaks the previous request's values into the next request.

The second TryIt shows both behaviors with real threads, plus a JSON formatter and a redaction helper.

Java MDC, JSON lines and redaction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Real MDC (org.slf4j.MDC) is the same idea backed by Logback's context; the JSON here is hand-built, whereas Boot's logging.structured.format.console produces complete ECS, Logstash or GELF records for you. Some frameworks propagate the MDC automatically across @Async tasks through a task decorator, but it is never automatic for plain threads.

Common mistakes

  • String concatenation in log calls. log.debug("user " + user) builds the string even when DEBUG is off. Use log.debug("user {}", user). If computing an argument is itself expensive, guard with if (log.isDebugEnabled()) or pass a supplier through the fluent API (log.atDebug().addArgument(() -> compute()).log("...")).
  • Losing the stack trace. log.error("failed: " + e.getMessage()) throws away where it failed. Pass the exception itself as the last argument.
  • Logging and rethrowing. If you log an exception and then throw it, the caller will usually log it again. Log where you handle the error, once.
  • Secrets and personal data. Never log passwords, tokens, full card numbers or whole request bodies. Check what toString() of a DTO or record prints, since records show every field.
  • Wrong levels. If everything is ERROR, nobody reads errors; if everything is INFO, nobody reads info. A failed user input is usually INFO or WARN, not ERROR.
  • System.out.println. It has no level, no timestamp, no MDC and no routing. Use a logger.
  • Leaving DEBUG on in production. Verbose SQL and HTTP logging costs CPU and disk and often contains user data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A logger named com.shop.payment.PaymentClient has no level of its own. Levels are set for root (INFO), com.shop (DEBUG) and com.shop.payment (WARN). Which level applies?

    The nearest configured ancestor in the name hierarchy wins, and com.shop.payment is closer than com.shop or root.
  2. 2. Why is log.debug("user " + user) worse than log.debug("user {}", user)?

    Concatenation runs before the call, so it costs time and memory even when the message is discarded. Placeholders are only filled in when the level is enabled.
  3. 3. What is the MDC used for?

    The Mapped Diagnostic Context makes values such as requestId available to the pattern or JSON output without passing them to every log call.
  4. 4. A request handler puts requestId in the MDC and then submits a task to a thread pool. What do the task's log lines contain?

    The MDC is thread-local, so another thread starts with an empty context. Copy it explicitly or use a task decorator that does so.
  5. 5. Which is the best way to log a caught exception?

    The exception as the last argument prints the stack trace. Logging it once, where it is handled, avoids duplicate entries.

Summary

  • Code logs through SLF4J; Boot's starter provides Logback as the backend, so you rarely touch the backend directly.
  • Levels come from logging.level.* and are inherited through the logger-name hierarchy; groups change several loggers at once.
  • Use {} placeholders instead of concatenation, and pass the exception as the last argument.
  • Format with logging.pattern.*, or switch to JSON with logging.structured.format.console for log platforms.
  • Put a correlation ID in the MDC in a filter, clear it in finally, and copy it explicitly to other threads.
  • Never log secrets or personal data, and log each error once.

Next: REST Controllers.