Sub topic 7
Logging exceptions correctly
This chapter assumes you can write try/catch blocks, know the System.Logger and SLF4J calls from the earlier chapters, and understand that a stack trace lists the call chain at the moment an exception was created. It covers how to pass an exception to a logger so the stack trace is kept, and where in your code to log it.
What a logged exception must contain
A useful error log entry answers three questions:
- What was the application trying to do, and with which input?
- What went wrong?
- Where did it go wrong?
The message you write answers the first question. The exception's type and message answer the second. The stack trace answers the third. The stack trace is a separate field on the log event, not part of the message text. Both logging APIs attach it only when you pass the exception as a Throwable argument in the right position. If you convert the exception to a string yourself, the trace is gone.
Passing the exception to System.Logger
System.Logger has overloads that take a Throwable as the last parameter:
log(Level level, String msg, Throwable thrown)log(Level level, Supplier<String> msgSupplier, Throwable thrown)
The varargs overload log(Level, String format, Object... params) is different. It treats every argument as a MessageFormat parameter, and the API does not treat a trailing Throwable specially there. Whether the trace appears depends on the backend, so you should not rely on it. No overload combines {0} placeholders with a Throwable. If you need context in the message, build the string yourself.
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class ExceptionDemo {
private static final Logger LOG = System.getLogger(ExceptionDemo.class.getName());
public static void main(String[] args) {
String orderId = "A-17";
try {
Integer.parseInt("12x");
} catch (NumberFormatException e) {
// Message only: no stack trace is recorded.
LOG.log(Level.ERROR, "Bad quantity in order " + orderId);
// Message plus Throwable: the stack trace is recorded.
LOG.log(Level.ERROR, "Bad quantity in order " + orderId, e);
}
}
}With the default java.util.logging backend, the second call prints the message followed by java.lang.NumberFormatException: For input string: "12x" and the stack frames. The first call prints only the message. Concatenating here is acceptable because the code runs only in the error path. In a hot path, use the Supplier overload with the Throwable, which defers the string building until the level is enabled.
Passing the exception to SLF4J
SLF4J handles this by convention. If the last argument is a Throwable and the message has no placeholder left for it, SLF4J treats it as the exception. This means you can combine context placeholders and the exception in one call:
log.error("Charge failed for customer {}", customerId, e);The {} receives customerId. The exception e has no placeholder, so it becomes the logged throwable. The table shows common forms and what each one records.
| Call | Stack trace recorded? | Comment |
|---|---|---|
| `log.error("Charge failed", e)` | Yes | Standard form. |
| `log.error("Charge failed for {}", id, e)` | Yes | Context plus exception. |
| `log.error("Charge failed: " + e)` | No | Only `e.toString()` ends up in the text. |
| `log.error(e.getMessage())` | No | Loses the type, the cause chain and the trace. `getMessage()` can also be `null`. |
| `log.error("Charge failed: {}", e.getMessage())` | No | The same loss, with a placeholder. |
| `e.printStackTrace()` | Not through the logger | Writes to `System.err` and bypasses levels, appenders and patterns. |
If a line in your logs shows an exception name but no at ... frames, check that the call matches one of the first two rows.
A complete SLF4J example
The next program wraps a low-level IOException in a domain exception and logs it once, at the boundary where it is handled. It compiles against slf4j-api and needs a provider such as Logback on the runtime classpath (see the earlier chapter on providers).
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InvoiceApp {
private static final Logger log = LoggerFactory.getLogger(InvoiceApp.class);
public static void main(String[] args) {
try {
new InvoiceService().process("INV-1001");
} catch (IllegalStateException e) {
log.error("Invoice run failed for {}", "INV-1001", e);
}
}
}
class InvoiceService {
void process(String invoiceId) {
try {
load(invoiceId);
} catch (IOException e) {
// Wrap, add context, keep the cause. Do not log here.
throw new IllegalStateException("Cannot load invoice " + invoiceId, e);
}
}
private void load(String invoiceId) throws IOException {
throw new IOException("Storage unavailable");
}
}The output contains two exception blocks. The first is the IllegalStateException with its frames. The second begins with Caused by: java.io.IOException: Storage unavailable. Passing the cause to the wrapping exception's constructor is what produces the second block. If you wrote new IllegalStateException("Cannot load invoice " + invoiceId) without e, the root cause would disappear and nobody could tell why storage failed.
Log once, at the place that handles the exception
Logging an exception at every layer is the most common mistake in real code. A request fails in a repository, the repository logs it and rethrows, the service logs it and rethrows, and the controller logs it again. One failure produces three stack traces. They look like three incidents, and they make log search and alert counts misleading.
Use this rule: either handle the exception or pass it up, and log it only where you handle it.
Some details of the rule:
- Wrapping and rethrowing is not handling. The code that finally decides what happens (an HTTP handler, a message consumer, the thread's top-level loop) is the code that logs.
- If you must catch and rethrow the same exception, for example to roll back a transaction, do the cleanup and do not log.
- Do not log an exception and then throw a new one without the original as its cause. That splits the story across two places and loses the link between them.
- Threads that end with an uncaught exception go to the thread's
UncaughtExceptionHandler, which prints toSystem.errby default. For worker threads, catchThrowableat the top of the task and log it there, or install a handler that calls your logger.
Choosing the level for an exception
An exception does not always mean ERROR. The level should describe the effect on the application, as covered in the chapter on levels.
- Use
ERRORwhen an operation failed and a person may need to act, such as a failed payment or a lost database connection. - Use
WARNING(WARNin SLF4J) when you recovered, such as a retry that succeeded or a fallback to a cached value. Include the exception only if the trace helps diagnosis. - Use
DEBUGor no logging for expected conditions, such as a user typing a non-numeric value into a form. Writing a full stack trace for routine bad input floods the logs and hides real faults.
For a recurring and expected failure, log a short message without the Throwable, and keep the trace for the unexpected case.
How the stack trace gets formatted
Logback does not need a conversion word in the pattern to print traces. If the pattern has no throwable converter, Logback appends %ex for you. You can control the output by naming a converter in the pattern. Add it after %msg and before %n:
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n%ex{short}</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>Here %ex{short} prints only the first line of the trace. The converter forms you are most likely to use are:
| Converter | Effect |
|---|---|
| `%ex` or `%exception` | Full trace, outermost exception first. This is the default. |
| `%ex{short}` | First line of the trace only. |
| `%ex{3}` | At most three frames per exception. |
| `%rEx` | Root cause first, which suits traces with long wrapper chains. |
| `%xEx` | Full trace with the jar and version of each frame. |
| `%nopex` | Suppress traces entirely. |
Use %nopex with caution. If a team member sets it to quiet the console and forgets, every log.error(..., e) loses its trace.
Pitfalls
- Secrets inside exceptions. Exception messages sometimes contain connection strings, tokens or personal data, for example
SQLExceptiontext or a custom exception that formats a request body. Logging the exception writes that text to disk. Keep sensitive values out of exception messages when you create them. - Huge or cyclic cause chains. Libraries that wrap exceptions repeatedly can produce traces with hundreds of frames. A depth limit such as
%ex{20}keeps entries readable. - Exceptions thrown while logging. A
toString()that throws inside a placeholder argument, or a supplier that throws, can fail the log call. Keep arguments simple and free of side effects. - Null exceptions. Passing a
nullThrowableis allowed and logs no trace, but it often points to a bug in the code that produced the variable. - Suppressed exceptions. A try-with-resources block that throws from both the body and
close()attaches the second exception as suppressed. Standard formatters print these underSuppressed:. Do not copy onlygetMessage()or you will lose them.
Exercise
A teammate writes log.warn("Retry {} failed: {}", attempt, e.getMessage()); in a retry loop, and later asks why the logs show "failed: null" with no stack trace. Explain the cause and give a corrected call.
Show answer
Some exceptions, such as NullPointerException thrown without a message, return null from getMessage(), and passing only the message discards the exception type and stack trace. Pass the exception itself as the last argument so SLF4J records it as the throwable: log.warn("Retry {} failed", attempt, e);. The two arguments fill only one placeholder, so e is the throwable.
Exercise
A service method catches SQLException, calls log.error("Query failed", e), and then throws new DataAccessException("Query failed"). The controller catches that and logs log.error("Request failed", ex). Name two problems and describe the fix.
Show answer
First, the same failure is logged twice at different layers, so it appears as two incidents. Second, the new exception does not carry the SQLException as its cause, so the second log entry has no link to the root cause. Fix it by removing the log call in the service method and throwing new DataAccessException("Query failed", e). The controller then logs once with the full cause chain.
Exercise
You call LOG.log(Level.ERROR, "Failed for {0}", id, e) on a System.Logger. Why is that not a reliable way to record the stack trace, and what should you write instead?
Show answer
The call matches the varargs overload log(Level, String, Object...), which treats id and e as MessageFormat parameters. The API does not define the trailing Throwable as the logged exception, so the result depends on the backend. Use the explicit overload with a Throwable parameter and build the context into the message: LOG.log(Level.ERROR, "Failed for " + id, e);.