Sub topic 6
Parameterized messages and avoiding wasted work
This chapter assumes basic Java classes and methods, try/catch, and familiarity with Maven or Gradle dependencies. You should also know the difference between a method call and a value passed to that method.
A log message often contains changing values:
Placing order A-1042 for customer C-77A naive implementation builds the complete string before calling the logger:
log.debug("Placing order " + orderId + " for customer " + customerId);This works, but Java performs the concatenation even when debug logging is disabled. A parameterized message keeps the template separate from its values. The logging implementation formats the message only when it needs to emit it.
Two placeholder styles
System.Logger uses java.text.MessageFormat-style placeholders. The first value uses {0}, the second uses {1}, and so on. SLF4J uses {} for each value.
| API | Template | Values |
|---|---|---|
| `System.Logger` | `"Order {0} costs {1}"` | `orderId`, `amount` |
| SLF4J | `"Order {} costs {}"` | `orderId`, `amount` |
The styles are not interchangeable. A {} placeholder passed to System.Logger is ordinary text, while {0} passed to SLF4J does not mean the same thing as an SLF4J placeholder.
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class OrderService {
private static final Logger LOG =
System.getLogger(OrderService.class.getName());
public void describe(String orderId, int itemCount) {
LOG.log(Level.INFO, "Order {0} contains {1} items",
orderId, itemCount);
LOG.log(Level.DEBUG,
() -> "Order " + orderId + " has " + itemCount + " items");
}
public static void main(String[] args) {
new OrderService().describe("A-1042", 3);
}
}The Supplier<String> overload accepts a lambda that creates the message later. The concatenation inside the lambda is skipped if DEBUG is disabled.
Parameterized messages do not make arguments lazy
Consider this call:
LOG.log(Level.DEBUG, "State: {0}", calculateExpensiveState());Java evaluates calculateExpensiveState() before it calls log. The logger can avoid formatting the message, but it cannot undo work that has already happened.
The same rule applies to SLF4J:
log.debug("State: {}", calculateExpensiveState());The {} placeholder avoids unnecessary string concatenation. It does not avoid evaluating calculateExpensiveState().
Use a level check when producing an argument is expensive:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReportService {
private static final Logger log =
LoggerFactory.getLogger(ReportService.class);
public void report(Report report) {
if (log.isDebugEnabled()) {
log.debug("Report details: {}", report.renderDetails());
}
}
public static void main(String[] args) {
new ReportService().report(new Report("monthly"));
}
private record Report(String name) {
String renderDetails() {
return "name=" + name + ", generated=true";
}
}
}For ordinary values such as an identifier, number, or short string, a normal parameterized call is usually enough. Do not surround every log statement with a level check. Checks make code longer and can reduce readability.
Understand the evaluation order
The logging call happens only after Java evaluates all method arguments. A lazy supplier changes that order for the message itself.
Practical rules
- Prefer
System.Loggerplaceholders such as{0}and{1}when using the JDK API. - Prefer SLF4J placeholders such as
{}when using SLF4J. - Do not concatenate strings before passing them to a logger.
- Remember that method arguments are eager by default.
- Guard expensive diagnostic work with the relevant level check.
- Avoid logging secrets merely because a message is at a low level. Disabled logs can become enabled in production.
Exercise
Why does log.debug("Result: {}", buildResult()) still call buildResult() when debug logging is disabled, and how can you avoid that work?
Show answer
Java evaluates buildResult() before invoking debug. Put the call inside if (log.isDebugEnabled()), or use an API overload that accepts a lazy supplier when available.