Sub topic 7
Logging exceptions correctly
Assume you know basic Java classes, try/catch, and how to add Maven or Gradle dependencies. This chapter focuses on recording exceptions with the JDK System.Logger API and the SLF4J facade.
An exception contains more information than its message. Its stack trace shows where the failure occurred. Its cause can show the lower-level failure that led to it. Good logging preserves this information without exposing secrets or producing duplicate log entries.
Log the exception object
With System.Logger, pass the exception to the overload that accepts a Throwable. The logger then records the message and stack trace together.
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 place(String orderId) {
try {
if (orderId == null || orderId.isBlank()) {
throw new IllegalArgumentException("Empty order id");
}
LOG.log(Level.INFO, "Order {0} validated", orderId);
} catch (IllegalArgumentException e) {
LOG.log(Level.ERROR, "Could not place order", e);
}
}
public static void main(String[] args) {
new OrderService().place("");
}
}The third argument in the ERROR call is the exception, not a value for {0}. The output includes the exception type, message, and stack trace.
You can also include a parameter and an exception:
LOG.log(Level.ERROR, "Could not place order {0}", orderId, e);Here, {0} receives orderId, and e supplies the stack trace through the overload that accepts arguments and a Throwable.
Log exceptions with SLF4J
SLF4J uses {} placeholders. Pass the exception as the final argument when the message has no matching placeholder for it.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PaymentService {
private static final Logger log =
LoggerFactory.getLogger(PaymentService.class);
public void charge(String customerId, long amountCents) {
try {
process(amountCents);
log.info("Charged customer {} amount {} cents",
customerId, amountCents);
} catch (IllegalStateException e) {
log.error("Charge failed for customer {}", customerId, e);
}
}
private void process(long amountCents) {
if (amountCents <= 0) {
throw new IllegalStateException("Amount must be positive");
}
}
}SLF4J replaces {} with the next argument. In the error call, there is one placeholder and one ordinary value, customerId. The final e has no placeholder, so SLF4J treats it as the throwable and prints its stack trace.
Avoid this mistake:
log.error("Charge failed: {}", e);This can format the exception as the placeholder value instead of recording it as the throwable. Use a message without a placeholder, or include a separate context value before the exception.
| Need | Correct approach |
|---|---|
| Record only a message | `log.error("Charge failed")` |
| Record a context value and stack trace | `log.error("Charge failed for {}", customerId, e)` |
| Record a different exception as the cause | `new ServiceException("...", e)` |
Preserve causes and avoid duplicate logs
When translating an exception at a boundary, preserve the original exception as the cause:
try {
paymentClient.charge(customerId);
} catch (PaymentTimeoutException e) {
throw new OrderProcessingException("Payment failed", e);
}The higher layer can log the resulting exception. Do not log the same exception at every layer and then rethrow it. That creates repeated stack traces. Log when the application can make a useful decision, such as returning an error response or ending a background job.
How the flow works
A useful log event answers what failed, which operation was involved, and which exception caused the failure. Keep the message stable enough for searching, and put variable identifiers in parameters or structured fields rather than concatenating them into the message.
Exercise
In SLF4J, how should you log an exception for customer ID "c-17" without losing its stack trace?
Show answer
Use log.error("Charge failed for customer {}", "c-17", exception);, with the exception as the final argument and no placeholder for it.