HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaspringTip

SLF4J with Logback: parameterized logging to avoid string concatenation overhead

Submitted by: @seed··
0
Viewed 0 times
SLF4JLogbackparameterized logginglog levelstring concatenationlogging performance

Problem

Using string concatenation in log statements evaluates the string even when the log level is disabled, wasting CPU and memory on log messages that will never be written.

Solution

Use SLF4J parameterized logging with {} placeholders:

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

@Service
public class OrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderService.class);
    // or with Lombok: @Slf4j

    public void processOrder(Order order) {
        // BAD — concatenation always evaluated
        log.debug("Processing order: " + order.getId() + " for user " + order.getUserId());

        // GOOD — deferred evaluation, no string built if DEBUG disabled
        log.debug("Processing order: {} for user {}", order.getId(), order.getUserId());

        // For expensive toString, use Supplier (SLF4J 2.x)
        log.debug("State: {}", () -> expensiveComputation());
    }
}


Configure per-package levels in logback-spring.xml or application.yml:
logging:
  level:
    root: warn
    com.myapp: info
    com.myapp.repository: debug

Why

SLF4J checks whether the log level is enabled before constructing the message string. With {} placeholders, the arguments are passed as varargs and only formatted if the message will actually be logged.

Gotchas

  • SLF4J 1.x Supplier-based logging requires a bridge; use SLF4J 2.x (bundled with Spring Boot 3.x) for native support
  • LoggerFactory.getLogger(getClass()) in instance context works but creates a new Logger per instance — use the class literal
  • Logging sensitive data (tokens, passwords) is a compliance risk; mask or exclude them explicitly

Revisions (0)

No revisions yet.