0Pricing
Java Academy · Lesson

Parameterized Logging

Efficient message formatting.

The Problem With String Concatenation

Concatenating a log message builds the full string before the call, even if the level is disabled.

log.debug("id=" + id + " name=" + name) wastes CPU when DEBUG is off, because the string is built regardless.

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

public class Main {
    private static final Logger log = LoggerFactory.getLogger(Main.class);
    public static void main(String[] args) {
        String name = "Ada"; int id = 7;
        // Bad: string is built even if DEBUG is disabled
        log.debug("id=" + id + " name=" + name);
    }
}

Placeholders With {}

SLF4J uses {} as a placeholder. Pass the values as extra arguments.

The message is only assembled if the level is enabled, so disabled logs cost almost nothing.

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

public class Main {
    private static final Logger log = LoggerFactory.getLogger(Main.class);
    public static void main(String[] args) {
        String name = "Ada"; int id = 7;
        // Good: no string built unless DEBUG is on
        log.debug("id={} name={}", id, name);
    }
}

All lessons in this course

  1. Why Structured Logging
  2. SLF4J Facade and Loggers
  3. Parameterized Logging
  4. Configuring Logback
← Back to Java Academy