Video in progress
If a debug log needs expensive data to be computed, how do lambdas and Supplier help?
In log.debug("x={}", expensive()), expensive() is computed even when debug is off, because arguments are evaluated before the method is called. APIs that accept a Supplier (the SLF4J 2 fluent API, Log4j2, java.util.logging, Objects.requireNonNull) do the computation only when it's needed.
📖 Answer
A typical case:
log.debug("Savat holati: {}", objectMapper.writeValueAsString(cart));
In prod debug is off, but JSON serialization runs on every request. In the profiler writeValueAsString shows up as hot, and nobody ever reads that log. The {} placeholder only postpones building the text, not evaluating the argument itself.
Options:
// 1) classic: check the level
if (log.isDebugEnabled()) {
log.debug("Savat holati: {}", toJson(cart));
}
// 2) SLF4J 2.x fluent API, with a Supplier (Spring Boot 3 brings this version)
log.atDebug()
.setMessage("Savat holati: {}")
.addArgument(() -> toJson(cart))
.log();
// 3) Log4j2's API directly
logger.debug("Savat holati: {}", () -> toJson(cart));
The same idea appears elsewhere in the JDK:
Objects.requireNonNull(order, () -> "order null, so'rov " + requestId); // the message is built only on failure
julLogger.fine(() -> "batafsil: " + dump());
A lambda isn't free: if it captures local variables, a small object is created on each call. For cheap arguments (id, size) a plain {} is enough: use a Supplier only for a genuinely expensive computation.
In code review, if I see serialization inside log.debug(, a toString() on a large collection or a DB call, I ask for one of these approaches.
Sign up to mark studied questions and save your progress.