Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 119 ยท Logging and Tooling

Logging with SLF4J and Logback

Log like a professional Java developer. Learn java.util.logging, the SLF4J API, Logback and Log4j 2 configuration, log levels, placeholders, MDC and JSON logs.

When a service misbehaves in production at 3 a.m., you cannot attach a debugger or add a println. What you have is the log: the trail of messages the application wrote while it ran. Good logs tell you what happened, to which request, in what order and why it failed. Bad logs are either silent at the critical moment or so noisy that the important line drowns.

This lesson shows how logging works in professional Java. You start with java.util.logging, which is built into the JDK and runs here, to understand loggers, levels, handlers and formatters. Then you meet the industry standard: the SLF4J API with Logback or Log4j 2 behind it, their configuration files, parameterized messages, the MDC for request context, and structured JSON logs. If logging is new to you, the beginner lesson Logging is a shorter introduction.

Why not System.out.println?

println works for a five-minute script, but a real application needs things it cannot do:

  • Levels. Turn detailed debug output on for one package while debugging, and off everywhere else, without changing code.
  • Metadata. Every line gets a timestamp, level, thread name and the logger (usually the class) that wrote it.
  • Destinations. Send logs to the console, rolling files, a log server or a JSON pipeline, by configuration.
  • Performance. Messages below the active level cost almost nothing, and writing can be buffered or asynchronous.
  • Context. Attach a request id or user id to every line written while handling one request.

Every logging framework is built from the same four parts:

Part Role
Logger the object your code calls; named, usually after the class (com.shop.CheckoutService)
Level how important a message is; each logger has a threshold below which messages are dropped
Handler / Appender where messages go: console, file, socket
Formatter / Layout / Encoder how a message is turned into text or JSON

java.util.logging: the JDK's built-in logger

java.util.logging (JUL) has shipped with Java since version 1.4. It needs no dependency, which makes it a good place to see the moving parts. Its levels, from most to least severe, are SEVERE, WARNING, INFO, CONFIG, FINE, FINER and FINEST.

Java java.util.logging out of the box

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 you see:

  • Each message takes two lines: a timestamp plus the class and method that logged it (Main main), then LEVEL: message. This is JUL's default SimpleFormatter.
  • The output goes to standard error, not standard output. That is JUL's ConsoleHandler default.
  • The fine message is missing. The root logger's level is INFO, so anything less severe is dropped before it is even formatted.

Hierarchy, handlers and formatters

Logger names form a hierarchy separated by dots. com.shop.db is a child of com.shop, which is a child of the root logger (named ""). A logger without its own level inherits its parent's, and by default every message also travels up to the parent's handlers. That is how one line of configuration (com.shop.db = FINE) turns on detail for one package only.

A message must pass two filters: the logger's level and the handler's level. This catches everyone out the first time: setting a logger to FINE is not enough if the console handler still only accepts INFO. The next example sets both, writes to standard output with a one-line custom formatter, and uses a Supplier so an expensive message is only built when it will actually be logged.

Java Levels, handlers and a custom formatter

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.

The (building the expensive dump) line appears only once: for the db logger, where FINE is enabled. That is the point of lazy messages. With string concatenation (checkout.fine("Cart dump: " + expensiveDump())), Java would build the string before calling fine, even though the message is then thrown away.

In a real application, JUL is configured with a logging.properties file passed as -Djava.util.logging.config.file=logging.properties, rather than in code.

System.Logger: the JDK's logging facade

Since Java 9 the JDK also has System.Logger, a tiny facade: an interface your code logs to, with the actual work done by whatever backend is installed. By default that backend is JUL, but SLF4J and Log4j 2 both provide adapters, so the same calls end up in their output instead. Libraries that want zero dependencies use it.

Java 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.

System.Logger levels are TRACE, DEBUG, INFO, WARNING and ERROR, the same names most of the ecosystem uses; with the JUL backend, ERROR is printed as SEVERE. Notice also Loaded 1,204 products: JUL fills placeholders with java.text.MessageFormat, which formats numbers for the current locale. SLF4J's {} placeholders call toString() and print 1204. JUL itself is rarely chosen for applications today: its configuration is clumsy and it lacks rolling files, async output and context. That gap is what SLF4J and Logback fill.

SLF4J: the API everybody logs to

SLF4J (Simple Logging Facade for Java) is a logging API with no real implementation of its own. Your code, and almost every library you depend on (Hibernate, Spring, Kafka clients), logs to SLF4J. At runtime, exactly one provider (a backend such as Logback or Log4j 2) on the classpath receives the messages. You can switch backends without touching a line of code, and all libraries end up in one consistent log.

XML
<!-- The API: what your code compiles against -->
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>2.0.20</version>
</dependency>
<!-- The provider: Logback (it pulls in slf4j-api too) -->
<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <version>1.6.5</version>
</dependency>

The code is the same with any provider:

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

public class CheckoutService {
    private static final Logger log = LoggerFactory.getLogger(CheckoutService.class);

    public Order checkout(Cart cart, String userId) {
        log.info("Checkout started for cart {} by user {}", cart.id(), userId);
        try {
            Order order = place(cart);
            log.debug("Order {} has {} lines", order.id(), order.lines().size());
            return order;
        } catch (PaymentException e) {
            log.warn("Payment failed for cart {}", cart.id(), e);   // exception LAST, no placeholder
            throw e;
        }
    }
}

The essentials:

  • One static final logger per class, named after the class. The name gives you the package hierarchy for configuration for free.
  • {} placeholders, never concatenation. log.debug("Order {} has {} lines", id, n) does no string work at all when DEBUG is off. Concatenation builds the string every time.
  • The exception goes last, without a placeholder of its own. SLF4J recognizes a trailing Throwable and prints its stack trace. log.error("Failed: " + e) loses the stack trace; log.error("Failed: {}", e.getMessage()) loses it too.
  • Guards are rarely needed. if (log.isDebugEnabled()) is only worth it when computing an argument is expensive. SLF4J 2 also offers lazy suppliers in its fluent API.
  • SLF4J 2's fluent API adds key-value pairs for structured logging:
Java
log.atInfo()
   .setMessage("Order placed")
   .addKeyValue("orderId", order.id())
   .addKeyValue("totalCents", order.totalCents())
   .log();

If no provider is on the classpath, SLF4J prints a warning and discards everything ("No SLF4J providers were found"). If several are present, it warns and picks one. Exactly one is the rule.

Bridging the other logging APIs

Java has a history of competing logging APIs, and your dependencies may use any of them. Bridges reroute them into SLF4J so everything reaches one backend:

Library logs to... Add this bridge
java.util.logging jul-to-slf4j (and install SLF4JBridgeHandler at startup)
Apache Commons Logging jcl-over-slf4j (Spring uses its own spring-jcl, already bridged)
Log4j 1.x API log4j-over-slf4j
Log4j 2 API (with Logback as backend) log4j-to-slf4j

Never put a bridge and its opposite binding on the classpath together (for example log4j-to-slf4j and log4j-slf4j2-impl), or messages loop forever.

Configuring Logback

Logback, written by SLF4J's author, is the default backend in Spring Boot. It reads logback.xml (or logback-test.xml in tests) from the classpath, usually src/main/resources:

XML
<configuration>
  <!-- Console: human-readable pattern -->
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <!-- File: rolls daily and at 50 MB, keeps 30 days, caps total size -->
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logs/shop.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
      <fileNamePattern>logs/shop.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
      <maxFileSize>50MB</maxFileSize>
      <maxHistory>30</maxHistory>
      <totalSizeCap>2GB</totalSizeCap>
    </rollingPolicy>
    <encoder>
      <pattern>%d{ISO8601} %-5level [%thread] %logger - %msg%n</pattern>
    </encoder>
  </appender>

  <!-- More detail for one package; quieter for a noisy library -->
  <logger name="com.shop.db" level="DEBUG"/>
  <logger name="org.hibernate.SQL" level="WARN"/>

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

The concepts map one to one onto JUL: <logger> sets levels per name, <root> is the root logger, appenders are handlers and encoders are formatters. Like JUL, messages flow up the hierarchy (additivity); <logger name="..." additivity="false"> stops them from also reaching the root's appenders. Useful pattern words: %d date, %level, %thread, %logger{36} (abbreviated to fit 36 characters), %msg, %n newline, %X{requestId} an MDC value, %ex the exception.

In Spring Boot you rarely write this file. Set levels in application.properties with logging.level.com.shop.db=DEBUG, and log files with logging.file.name; use logback-spring.xml for anything more.

Log4j 2 as the alternative

Log4j 2 is the other major backend, from the Apache Software Foundation, known for its high-throughput asynchronous loggers. With SLF4J in front, you swap logback-classic for org.apache.logging.log4j:log4j-slf4j2-impl and configure log4j2.xml:

XML
<Configuration status="WARN">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level [%t] %c{1.} - %msg%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Logger name="com.shop.db" level="debug"/>
    <Root level="info">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

In December 2021, Log4Shell (CVE-2021-44228) showed what a logging library can do when it is out of date: Log4j 2 versions up to 2.14 would evaluate ${jndi:ldap://...} lookups inside logged messages, letting attackers run code by sending a crafted header. The fixes have long been released. The lesson is general: keep logging libraries patched like any other dependency, and never trust text you log.

Choosing log levels

SLF4J, Logback and Log4j 2 share five levels. A sensible convention:

Level Use for Example
ERROR a failure that needs attention; an operation could not be completed "Payment provider returned 500 for order 42"
WARN something unexpected that the application recovered from "Retrying payment (attempt 2 of 3)"
INFO important business or lifecycle events, a few per request at most "Order 42 placed", "Started in 2.3 s"
DEBUG detail for developers diagnosing a problem "Loaded 3 cart lines in 4 ms"
TRACE very fine detail, usually off even when debugging "Entering calculateTax(...)"

Production normally runs at INFO. Log an exception once, where it is handled, not at every layer it passes through, or one failure produces five stack traces. And remember that logs are read by people under pressure: say what happened and include the identifiers needed to find it (order id, user id), not just "Error!".

Context with MDC

When a server handles hundreds of requests at once, their log lines interleave. The Mapped Diagnostic Context (MDC) attaches key-value pairs to the current thread, and the layout prints them on every line written by that thread:

Java
// In a servlet filter or interceptor, once per request:
try (var ignored = MDC.putCloseable("requestId", requestId)) {
    chain.doFilter(request, response);     // every log line inside gets the requestId
}

With %X{requestId} in the Logback pattern, you can then search the log for one request's complete story. Two cautions: the MDC is thread-local, so always clear it (putCloseable or MDC.clear() in finally), because pooled threads otherwise carry stale ids into the next request; and it does not follow work to other threads automatically, so executors and async code must copy it (MDC.getCopyOfContextMap() / setContextMap(...)).

Structured JSON logs

Log aggregation systems (Elasticsearch/OpenSearch, Grafana Loki, Datadog, Splunk) work best with structured logs: one JSON object per line, with fields instead of free text. You can then query level:ERROR AND orderId:42 instead of writing regular expressions. Logback ships a JsonEncoder, the logstash-logback-encoder library is widely used, and Spring Boot 3.4 and later can switch to formats like Elastic Common Schema with one property (logging.structured.format.console=ecs).

The example below builds the idea from scratch with what is available here: a thread-local context map (a mini MDC) and a JUL formatter that writes each record as one JSON line with Jackson. Two threads handle two requests, and every line carries its request id.

Java A mini MDC and JSON log lines

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.

Each line is a complete JSON object such as {"level":"WARNING","logger":"com.shop.Checkout","thread":"worker-2","message":"Checkout failed","requestId":"req-91bc","user":"bo","error":"java.lang.IllegalStateException: card expired"}. The last line has no requestId, because the context was cleared. A real MDC works exactly like this, and real JSON encoders add timestamps, stack traces and the SLF4J key-value pairs.

What not to log

  • Secrets and credentials: passwords, API keys, tokens, session cookies, full card numbers. Logs are copied to many systems and kept for months.
  • Personal data beyond what you need. Privacy laws such as the GDPR apply to logs too. Log a user id rather than a name and email address.
  • Unsanitized user input in text logs. A value containing a newline can forge a fake log line (log injection). Structured JSON logs escape it automatically; text patterns in Logback can use %replace or encode newlines.
  • Whole objects by accident. log.info("User: {}", user) calls toString(), which may include the password hash. Records print every component, so check what yours expose.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A JUL logger is set to FINE, but its FINE messages still do not appear on the console. What is the most likely cause?

    A message must pass both the logger's level and the handler's level. The default ConsoleHandler only accepts INFO and above.
  2. 2. Why is log.debug("Cart: {}", cart) better than log.debug("Cart: " + cart) when DEBUG is off?

    With {} placeholders, SLF4J formats the message only if the level is enabled. Concatenation runs before the call, whether or not the message is logged.
  3. 3. Which call logs the exception's stack trace with SLF4J?

    SLF4J treats a trailing Throwable argument without its own placeholder as the exception to print with its full stack trace.
  4. 4. What does SLF4J do if two providers (say Logback and Log4j 2) are on the classpath?

    SLF4J warns about multiple providers and binds to one. The rule is exactly one provider per application.
  5. 5. Why must MDC values be cleared at the end of a request?

    Server threads are reused. Without clearing, a later request on the same thread would log with a stale request id or user.

Summary

  • Logging = loggers (named, hierarchical), levels, handlers/appenders (where) and formatters/encoders (how).
  • java.util.logging is built in: levels SEVERE to FINEST, output to stderr by default, and both the logger and the handler level must allow a message. System.Logger is the JDK's small facade.
  • In applications, code logs to the SLF4J API with exactly one provider: Logback (Spring Boot's default) or Log4j 2. Bridges route JUL, Commons Logging and Log4j APIs into it.
  • Use one static final logger per class, {} placeholders, the exception as the last argument, and levels with clear meanings (production at INFO).
  • Configure levels per package and rolling files in logback.xml or log4j2.xml; in Spring Boot, use logging.level.* properties.
  • Use the MDC for request context (and always clear it), prefer structured JSON logs for aggregation, and never log secrets or raw personal data.

Next: Debugging and Profiling Tools, for when the logs are not enough.