Skip to lesson

Parameterised log messages

A ShopLite payment fails and the log says only null, or the same stack trace appears three times. Good log lines are cheap to write, complete, and written once.

{} placeholders instead of string concatenation

A placeholder is a gap in a log message that the logger fills from an argument: {} in SLF4J, {0} and {1} in System.Logger and java.util.logging.

Joining strings with + builds the whole message even when the level is off. A placeholder lets the logger decide first.

Java
// SLF4J (Spring Boot)log.debug("Checking " + cart + " for customer " + customerId);   // joined every timelog.debug("Checking {} for customer {}", cart, customerId);        // joined only if DEBUG is on

Example 1 · Placeholders skip the work when the level is off

PlaceholderCostDemo.javaJava
import java.lang.System.Logger;import java.lang.System.Logger.Level;import java.util.List;
class Cart {    static int toStringCalls = 0;    private final int customerId;    private final List<String> skus;
    Cart(int customerId, List<String> skus) {        this.customerId = customerId;        this.skus = skus;    }
    @Override    public String toString() {        toStringCalls++;          // count how often the text is really built        return "Cart[customer=" + customerId + ", skus=" + skus + "]";    }}
public class PlaceholderCostDemo {    static {   // only for this page: log lines on System.out, without the date line        System.setErr(System.out);        System.setProperty("java.util.logging.SimpleFormatter.format", "%4$-7s %5$s%n");    }
    private static final Logger log = System.getLogger("com.shoplite.cart.CartService");
    public static void main(String[] args) {        Cart cart = new Cart(1, List.of("BK-CLEAN", "ACC-AD141"));
        for (int i = 0; i < 1000; i++) {            log.log(Level.DEBUG, "Checking " + cart);        }        System.out.println("Concatenation, DEBUG off: toString ran " + Cart.toStringCalls + " times");
        Cart.toStringCalls = 0;        for (int i = 0; i < 1000; i++) {            log.log(Level.DEBUG, "Checking {0}", cart);        }        System.out.println("Placeholder,   DEBUG off: toString ran " + Cart.toStringCalls + " times");
        log.log(Level.INFO, "Order {0} placed for {1}", 17, cart);        System.out.println("After one INFO line: toString ran " + Cart.toStringCalls + " time");    }}
Output
Concatenation, DEBUG off: toString ran 1000 times
Placeholder,   DEBUG off: toString ran 0 times
INFO    Order 17 placed for Cart[customer=1, skus=[BK-CLEAN, ACC-AD141]]
After one INFO line: toString ran 1 time

What this code does

  • With "Checking " + cart the cart's toString() ran 1000 times to build lines that were thrown away. With "Checking {0}", cart it never ran, because the logger checked the level first.
  • When a line is really written (the INFO call), the logger fills the gaps once. System.Logger uses {0}, {1}; SLF4J uses {} in the same way.

With "Checking " + cart Java joins the string, and calls cart.toString(), before debug even starts. With a placeholder the logger first checks the level and builds the text only if the line will be written.

The message also stays the same fixed text on every call, which makes lines easy to search.

MessageFormat placeholders format numbers for people: {0} with 19298 prints 19,298. Use {0,number,#} or pass String.valueOf(n) for ids and amounts. SLF4J's {} simply calls String.valueOf.

The exception as the last argument

A stack trace is the list of method calls that were running when an exception was thrown, plus every Caused by below it.

To keep the cause of a failure, pass the exception object itself as the last argument, with no {} for it.

Example 2 · src/main/java/com/shoplite/payment/PaymentService.java (exception last)

Runs in: the shoplite-api Spring Boot project

PaymentService.javaJava
// src/main/java/com/shoplite/payment/PaymentService.java (the logging parts)package com.shoplite.payment;
import java.math.BigDecimal;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Service;
@Servicepublic class PaymentService {
    private static final Logger log = LoggerFactory.getLogger(PaymentService.class);
    private final UpiGateway gateway;
    PaymentService(UpiGateway gateway) {        this.gateway = gateway;    }
    /** Returns false when the gateway fails; the order then stays "payment pending". */    public boolean collect(int orderId, BigDecimal amount) {        log.debug("Collecting Rs {} for order {}", amount, orderId);        try {            gateway.charge(orderId, amount);            log.info("Order {} paid: Rs {}", orderId, amount);            return true;        } catch (GatewayTimeoutException e) {            // Wrong: two {} but the exception is taken out as the stack trace, so the second {} stays empty            log.error("Payment failed for order {}: {}", orderId, e);
            // Right: one {} per value, the exception last and without a {}            log.error("Payment failed for order {} (Rs {})", orderId, amount, e);            return false;        }    }}
Sample output (stack traces trimmed to three frames)
2026-10-16T11:05:42.913+05:30 ERROR 14872 --- [shoplite-api] [nio-8080-exec-7] com.shoplite.payment.PaymentService      : Payment failed for order 17: {}

com.shoplite.payment.GatewayTimeoutException: UPI gateway timed out after 10 s
	at com.shoplite.payment.UpiGateway.charge(UpiGateway.java:41) ~[classes/:na]
	at com.shoplite.payment.PaymentService.collect(PaymentService.java:25) ~[classes/:na]
	at com.shoplite.order.OrderService.place(OrderService.java:88) ~[classes/:na]

2026-10-16T11:05:42.915+05:30 ERROR 14872 --- [shoplite-api] [nio-8080-exec-7] com.shoplite.payment.PaymentService      : Payment failed for order 17 (Rs 3097.00)

com.shoplite.payment.GatewayTimeoutException: UPI gateway timed out after 10 s
	at com.shoplite.payment.UpiGateway.charge(UpiGateway.java:41) ~[classes/:na]
	at com.shoplite.payment.PaymentService.collect(PaymentService.java:25) ~[classes/:na]
	at com.shoplite.order.OrderService.place(OrderService.java:88) ~[classes/:na]

What this code does

  • Both calls print the stack trace, because e is the last argument. In the first call the logger took e for the trace, so the second {} had no value and stayed as {}.
  • The fixed line has one {} per value (orderId, amount) and the exception last with no {} of its own.

In SLF4J write log.error("Payment failed for order {}", orderId, e). If the last argument is a Throwable, Logback prints it as a stack trace under the message. In JUL use log.log(Level.SEVERE, "message", e).

The stack trace is the most useful part of an error log, and you get it only when you pass the exception object itself.

Fix the error

Keep the stack trace

Read what the log printed, then pick the line that fixes it.

Round 1 of 2

The log shows a stray {} where the exception should be. Fix the log call.

try {
gateway.charge(orderId);
} catch (GatewayException e) {
log.error("Payment failed for order {}: {}", orderId, e);
}

Error

ERROR Payment failed for order 17: {}
com.shoplite.payment.GatewayException: timeout
log.error("Payment failed for order {}: {}", orderId, e) is a classic slip: Logback takes e out for the stack trace, so the second {} is printed as literal {}.

Why log.error(e.getMessage()) loses information

Here one failure is logged twice: first with getMessage() only, then with the whole exception. Compare the two outputs.

Example 3 · getMessage() vs the whole exception

LostStackTraceDemo.javaJava
import java.sql.SQLException;import java.util.logging.Level;import java.util.logging.Logger;
class OrderSaveException extends RuntimeException {    OrderSaveException(String message, Throwable cause) {        super(message, cause);    }}
public class LostStackTraceDemo {    static {   // only for this page: log lines on System.out, without the date line        System.setErr(System.out);        System.setProperty("java.util.logging.SimpleFormatter.format", "%4$-7s %5$s%6$s%n");    }
    private static final Logger log = Logger.getLogger("com.shoplite.order.OrderService");
    static void insertOrder(int orderId) throws SQLException {        throw new SQLException("Deadlock found when trying to get lock");    }
    static void saveOrder(int orderId) {        try {            insertOrder(orderId);        } catch (SQLException e) {            throw new OrderSaveException("Could not save order " + orderId, e);        }    }
    public static void main(String[] args) {        try {            saveOrder(17);        } catch (OrderSaveException e) {            System.out.println("--- Wrong: only the message ---");            log.severe(e.getMessage());
            System.out.println("--- Right: the exception as the last argument ---");            log.log(Level.SEVERE, "Order 17 failed", e);        }    }}
Output
--- Wrong: only the message ---
SEVERE  Could not save order 17
--- Right: the exception as the last argument ---
SEVERE  Order 17 failed
OrderSaveException: Could not save order 17
	at LostStackTraceDemo.saveOrder(LostStackTraceDemo.java:27)
	at LostStackTraceDemo.main(LostStackTraceDemo.java:33)
Caused by: java.sql.SQLException: Deadlock found when trying to get lock
	at LostStackTraceDemo.insertOrder(LostStackTraceDemo.java:20)
	at LostStackTraceDemo.saveOrder(LostStackTraceDemo.java:25)
	... 1 more

What this code does

  • The message-only line says the save failed but not why. The real reason, a database deadlock, is only in the Caused by part, which getMessage() drops.
  • log(Level.SEVERE, "Order 17 failed", e) keeps the type, the failing lines (saveOrder line 27, insertOrder line 20) and the cause. ... 1 more means the remaining frame is the same as in the trace above it.

getMessage() returns only the exception's own text, such as "Could not save order 17". It drops the exception type, the line that threw it and the whole Caused by chain, which usually holds the real reason, like a database deadlock.

Some exceptions have no message at all, and then the log line just says null. When you catch an exception you are not handling, either log the whole object or, better, wrap it with context and throw it on.

Expensive messages: level checks and suppliers

A supplier is a lambda () -> text that the logger calls only if the line is written, so a costly message is never built for a level that is switched off.

Placeholders delay joining the text, but Java still evaluates every argument first. Count how often a slow method runs under three styles.

Example 4 · Level check and supplier for a costly argument

ExpensiveMessageDemo.javaJava
import java.lang.System.Logger;import java.lang.System.Logger.Level;import java.util.List;
public class ExpensiveMessageDemo {    static {   // only for this page: log lines on System.out, without the date line        System.setErr(System.out);        System.setProperty("java.util.logging.SimpleFormatter.format", "%4$-7s %5$s%n");    }
    private static final Logger log = System.getLogger("com.shoplite.report.SalesReport");    static int slowCalls = 0;
    /** Pretend this reads every order of the day from the database. */    static String dailySummary(List<Integer> totals) {        slowCalls++;        int sum = totals.stream().mapToInt(Integer::intValue).sum();        return totals.size() + " orders, Rs " + sum;    }
    public static void main(String[] args) {        List<Integer> totals = List.of(3097, 19298, 1698);
        log.log(Level.DEBUG, "Summary: {0}", dailySummary(totals));   // argument runs first        System.out.println("Placeholder only: slow calls = " + slowCalls);
        slowCalls = 0;        if (log.isLoggable(Level.DEBUG)) {                             // level check            log.log(Level.DEBUG, "Summary: {0}", dailySummary(totals));        }        System.out.println("Level check:      slow calls = " + slowCalls);
        log.log(Level.DEBUG, () -> "Summary: " + dailySummary(totals));        System.out.println("Supplier:         slow calls = " + slowCalls);
        log.log(Level.INFO, () -> "Summary: " + dailySummary(totals));        System.out.println("Supplier at INFO: slow calls = " + slowCalls);    }}
Output
Placeholder only: slow calls = 1
Level check:      slow calls = 0
Supplier:         slow calls = 0
INFO    Summary: 3 orders, Rs 24093
Supplier at INFO: slow calls = 1

What this code does

  • The plain placeholder still ran dailySummary once: Java evaluates arguments before calling log. The level check and the supplier both skipped it while DEBUG was off.
  • At INFO the supplier is called, because that line is really written. Use these tools only for arguments that cost real work; for plain values a placeholder is enough.

log.debug("Summary: {}", dailySummary()) runs dailySummary() even when DEBUG is off. For an argument that costs real work, wrap the call in a level check, if (log.isDebugEnabled()) { ... }, or pass a supplier. System.Logger and JUL take a Supplier<String>; SLF4J 2 has the fluent form log.atDebug().addArgument(() -> dailySummary()).log("Summary: {}").

Log and rethrow: the same error twice

Log and rethrow means catching an exception, logging it, and throwing it again, so every layer writes the same error once more.

A failed refund passes through three layers. First every layer logs and rethrows; then the same failure is logged once.

Example 5 · Log and rethrow vs wrap and log once

LogOnceDemo.javaJava
import java.util.logging.Level;import java.util.logging.Logger;
class GatewayException extends RuntimeException {    GatewayException(String message, Throwable cause) {        super(message, cause);    }}
public class LogOnceDemo {    static {   // only for this page: one line per log call, no stack trace text        System.setErr(System.out);        System.setProperty("java.util.logging.SimpleFormatter.format", "%4$-7s %3$s: %5$s%n");    }
    private static final Logger clientLog = Logger.getLogger("UpiClient");    private static final Logger serviceLog = Logger.getLogger("PaymentService");    private static final Logger controllerLog = Logger.getLogger("OrderController");
    // ---- Wrong: every layer logs and rethrows ----    static void callGatewayNoisy() {        IllegalStateException e = new IllegalStateException("timed out after 10 s");        clientLog.log(Level.SEVERE, "Gateway call failed", e);        throw e;    }
    static void payNoisy() {        try {            callGatewayNoisy();        } catch (IllegalStateException e) {            serviceLog.log(Level.SEVERE, "Payment failed", e);            throw e;        }    }
    // ---- Right: add context on the way up, log once at the top ----    static void callGateway() {        throw new IllegalStateException("timed out after 10 s");    }
    static void pay(int orderId) {        try {            callGateway();        } catch (IllegalStateException e) {            throw new GatewayException("Payment for order " + orderId + " failed", e);        }    }
    public static void main(String[] args) {        System.out.println("--- Log and rethrow ---");        try {            payNoisy();        } catch (IllegalStateException e) {            controllerLog.log(Level.SEVERE, "Request failed", e);        }
        System.out.println("--- Wrap and log once ---");        try {            pay(17);        } catch (GatewayException e) {            controllerLog.log(Level.SEVERE, e.getMessage() + " (cause: " + e.getCause().getMessage() + ")", e);        }    }}
Output
--- Log and rethrow ---
SEVERE  UpiClient: Gateway call failed
SEVERE  PaymentService: Payment failed
SEVERE  OrderController: Request failed
--- Wrap and log once ---
SEVERE  OrderController: Payment for order 17 failed (cause: timed out after 10 s)

What this code does

  • One timeout produced three SEVERE lines (each with its own stack trace in a real log). Anyone counting errors would think three things broke.
  • In the fixed version the lower layer adds context ("order 17") by wrapping the exception, and only the top layer logs, once, with the cause still attached.

Each layer that logs and rethrows writes the same stack trace again, so one failure looks like three and alert counts become wrong.

The rule: handle it or pass it on, not both. Lower layers wrap the exception with context (new PaymentFailedException("Payment for order 17 failed", e)) and throw. One place at the top logs it once, with the full chain. In ShopLite that place is GlobalExceptionHandler, which logs unexpected 500 errors with their stack trace.

Order of execution

Log an error once

Put the steps in the order a failed refund should travel.

Next step

Check your understanding

10 quick questions