Sub topic 6
Parameterized messages and avoiding wasted work
This chapter assumes you can already write a log statement with System.Logger or SLF4J and know the standard levels (TRACE through ERROR). Here you will learn how placeholders defer message formatting, which work they cannot defer, and how to stop expensive arguments from running when a level is off.
The cost of a log call that prints nothing
A log statement at a disabled level should cost almost nothing. Whether it does depends on how you build the message. Compare these two lines:
LOG.log(Level.DEBUG, "Order " + order + " has " + items.size() + " items");
LOG.log(Level.DEBUG, "Order {0} has {1} items", order, items.size());In the first line, Java builds the full string before the logger is called. That means order.toString() runs, the concatenation allocates, and the result is thrown away if DEBUG is disabled. In the second line, the logger receives the template and the raw arguments. It checks the level first and formats only if the message will be written.
The second line is not free. The varargs array is still allocated, items.size() is still evaluated, and primitives are boxed. The savings come from skipping toString() calls and string building, which are usually the expensive part.
Mermaid diagrams must use the required fence, so here it is in full:
The diagram shows the key limit. Step A happens before any logger code runs, so placeholders cannot save you from an expensive argument expression.
Placeholders in System.Logger
System.Logger uses java.text.MessageFormat syntax: numbered placeholders such as {0} and {1}.
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class ShipmentLog {
private static final Logger LOG = System.getLogger(ShipmentLog.class.getName());
public static void main(String[] args) {
LOG.log(Level.INFO, "Shipment {0} left {1} with {2} parcels", "S-17", "Rotterdam", 1200);
}
}With the default java.util.logging backend, the message prints as Shipment S-17 left Rotterdam with 1,200 parcels. Notice 1,200. MessageFormat formats numbers using the default locale, so a German locale prints 1.200. This surprises people who search logs for an ID such as order 1234567, because the log contains 1,234,567. Convert identifiers to strings yourself (String.valueOf(id)) when you need them verbatim.
Two more MessageFormat rules matter in practice:
- A single quote starts a quoted section, so
"Can't place order {0}"drops the quote and may not substitute{0}. Write"Can''t place order {0}". - When you pass no arguments, the JDK default implementation does not run
MessageFormat. A message with a literal{0}and no arguments prints as written.
Placeholders in SLF4J
SLF4J uses anonymous {} placeholders. Each {} takes the next argument in order.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ShipmentLogSlf4j {
private static final Logger log = LoggerFactory.getLogger(ShipmentLogSlf4j.class);
public static void main(String[] args) {
log.info("Shipment {} left {} with {} parcels", "S-17", "Rotterdam", 1200);
}
}SLF4J does no locale-aware number formatting, so this prints 1200. It also has no quote-escaping rules. To print a literal {}, escape the opening brace with a backslash: "Empty set is \\{}" in Java source.
| Feature | System.Logger | SLF4J |
|---|---|---|
| Placeholder syntax | `{0}`, `{1}` (`MessageFormat`) | `{}` (positional) |
| Numbers | Locale-formatted (`1,200`) | `toString()` (`1200`) |
| Single quote | Must be doubled | No special meaning |
| Supplier overload | `log(Level, Supplier<String>)` | `log.atInfo().log(Supplier<String>)` (fluent API) |
| Level check | `isLoggable(Level)` | `isDebugEnabled()` and similar |
Arguments are still evaluated
Placeholders defer formatting but not argument evaluation. This is the most common source of wasted work:
log.debug("Cart state: {}", cart.toDetailedReport());toDetailedReport() runs on every call, even when DEBUG is off. The logger receives only the finished string. Placeholders help only when the argument is a cheap reference whose toString() is expensive, such as cart.
You have three tools to avoid this work.
Tool 1: a Supplier
The System.Logger supplier overload runs the lambda only if the level is enabled. This program demonstrates it.
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class LazyDemo {
private static final Logger LOG = System.getLogger(LazyDemo.class.getName());
private static int calls = 0;
static String expensive() {
calls++;
return "snapshot-" + calls;
}
public static void main(String[] args) {
LOG.log(Level.DEBUG, "Eager: " + expensive());
LOG.log(Level.DEBUG, () -> "Lazy: " + expensive());
System.out.println("expensive() ran " + calls + " time(s)");
}
}With the JDK default backend (java.util.logging, root level INFO), DEBUG is disabled. The eager line still calls expensive() because Java evaluates the argument first. The lazy line never runs its lambda. The program prints expensive() ran 1 time(s).
Tool 2: a level guard
A guard wraps several statements, or code that is not a single expression.
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class GuardDemo {
private static final Logger LOG = System.getLogger(GuardDemo.class.getName());
public static void main(String[] args) {
if (LOG.isLoggable(Level.TRACE)) {
String details = String.join(",", args);
LOG.log(Level.TRACE, "Arguments: {0}", details);
}
LOG.log(Level.INFO, "Started with {0} arguments", args.length);
}
}The SLF4J equivalent is if (log.isDebugEnabled()) { ... }. SLF4J has one check method per level: isTraceEnabled(), isDebugEnabled(), isInfoEnabled(), isWarnEnabled() and isErrorEnabled().
Tool 3: the SLF4J 2.x fluent API
The fluent API accepts suppliers for the whole message and for individual arguments. This keeps the {} template and still defers the expensive call.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FluentLazy {
private static final Logger log = LoggerFactory.getLogger(FluentLazy.class);
static String report() {
return "large report";
}
public static void main(String[] args) {
log.atDebug()
.addArgument(() -> report())
.log("Cart state: {}");
log.atDebug().log(() -> "Cart summary: " + report());
}
}When DEBUG is disabled, atDebug() returns a no-operation builder, and neither supplier runs. This needs slf4j-api 2.0 or later and a provider that supports it. Logback 1.3 and later does.
Choosing between the tools
| Situation | Use |
|---|---|
| Arguments are existing variables or simple getters | Plain placeholders |
| One expensive expression | Supplier, or the fluent `addArgument(Supplier)` |
| Several statements needed to build the data | `isLoggable` or `isDebugEnabled` guard |
| Message needs no arguments at all | A plain string literal |
A guard is not wrong for cheap messages, but it adds noise. Do not guard every statement.
Common errors
Mismatched placeholder count. SLF4J does not throw if the counts differ. With too few arguments, the extra {} stays in the output. With too many, the extra arguments are dropped (unless the last one is a Throwable, which is logged as a stack trace). Check the count when you edit a message. Some IDE inspections and static analysis tools flag these mismatches.
Concatenation inside a placeholder call. Code such as log.info("User " + id + " logged in from {}", ip) defeats the purpose and breaks if id contains {}. Put every variable in a placeholder.
Wrong placeholder style for the API. Writing {} in a System.Logger message, or {0} in an SLF4J message, prints the braces literally in most setups. Match the syntax to the API you called.
Side effects in log arguments. If an argument changes state, such as iterator.next() or counter.incrementAndGet(), the program behaves differently depending on log level. A supplier makes this worse, because the effect runs only when logging is on. Keep log arguments free of side effects.
Mutable arguments formatted later. With synchronous appenders, formatting happens in the calling thread, so the value is captured at the log call. If you use an asynchronous appender, the formatting may run later on another thread, and a mutable object could have changed by then. Pass immutable values or copy them first.
Exceptions and placeholders
Placeholders interact with exceptions in one specific way. In SLF4J, if the last argument is a Throwable and no placeholder is left for it, the logger treats it as the exception and prints its stack trace:
log.error("Charge failed for customer {}", customerId, e);The {} takes customerId, and e is logged with its stack trace. The next chapter covers exception logging in detail, including the System.Logger overload that takes a Throwable as a separate parameter.
Exercise
A teammate writes log.debug("Inventory: {}", warehouse.buildFullReport()); and says the placeholder means the report is only built when DEBUG is on. Is that correct? Rewrite the statement so the report is built only when DEBUG is enabled.
Show answer
No. Java evaluates warehouse.buildFullReport() before log.debug is called, so the report is built on every call. The placeholder only defers formatting of the already-built argument. Use the SLF4J 2.x fluent API: log.atDebug().addArgument(() -> warehouse.buildFullReport()).log("Inventory: {}");. A guard also works: if (log.isDebugEnabled()) { log.debug("Inventory: {}", warehouse.buildFullReport()); }.
Exercise
Why does System.Logger print Order 1,234,567 for LOG.log(Level.INFO, "Order {0}", 1234567L), and how do you make it print Order 1234567?
Show answer
System.Logger uses MessageFormat, which formats numbers according to the default locale and adds grouping separators. Convert the value to a string before logging: LOG.log(Level.INFO, "Order {0}", String.valueOf(1234567L)).