Sub topic 13
Choosing an API and Logging Best Practices
This chapter pulls the earlier material together into decision criteria and working habits. It assumes you can add Maven or Gradle dependencies and handle exceptions with try/catch. It also assumes you have seen System.Logger, SLF4J, Logback configuration, MDC and the platform logging bridge from the earlier chapters. Module-system knowledge helps but is not required.
Choosing between System.Logger and SLF4J
Both APIs are facades. Your code calls the facade, and a backend decides where the output goes. The two differ in where they come from and what they cost you.
| Question | System.Logger | SLF4J |
|---|---|---|
| Where does it come from? | The JDK (`java.base`, Java 9+) | An external `slf4j-api` dependency |
| Extra dependency needed to compile? | None | `slf4j-api` |
| Placeholder syntax | `{0}`, `{1}` (`MessageFormat`) | `{}` |
| Exception handling | Separate overload `log(Level, String, Throwable)` | Last argument is taken as the exception |
| Warning level name | `WARNING` | `WARN` |
| MDC | Not available | `MDC` class |
| Key-value pairs | Not available | Fluent API in 2.x |
| Backend selection | `System.LoggerFinder` (service lookup) | SLF4J provider (service lookup) |
The decision usually follows from what you are building.
- A library that wants no third-party dependency. Use
System.Logger. Consumers get log output without adding anything, and they can redirect it with the bridge. - An application, or a library inside an SLF4J-based ecosystem. Use SLF4J. You get MDC, the fluent API and a wide choice of backends and encoders.
- A library that is only ever used inside applications you control. Either works. Pick the one your applications already use, so there is one logging convention.
The next diagram shows the same choice as a flow.
The choice is not permanent. Because slf4j-jdk-platform-logging routes System.Logger calls into SLF4J, a library written against System.Logger still follows the application's Logback configuration. Do not mix APIs inside one class, because it makes the code harder to read and search.
Differences that cause bugs
Moving between the two APIs is where most mistakes happen. The syntax looks similar, but the formatting rules differ.
Placeholder syntax is not interchangeable
System.Logger formats with java.text.MessageFormat, so {} does nothing and the argument is silently dropped.
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class PlaceholderMistake {
private static final Logger LOG = System.getLogger(PlaceholderMistake.class.getName());
public static void main(String[] args) {
LOG.log(Level.INFO, "Order {} shipped", "A-17"); // wrong: prints "Order {} shipped"
LOG.log(Level.INFO, "Order {0} shipped", "A-17"); // right: prints "Order A-17 shipped"
}
}The reverse mistake in SLF4J, writing {0}, also fails. SLF4J treats it as literal text.
MessageFormat has side effects
When you pass arguments, MessageFormat rules apply to the whole pattern.
- A single apostrophe starts quoted text, so
"Can't place order {0}"can lose the placeholder. Write''for a literal apostrophe, or avoid apostrophes. - Numbers are formatted for the default locale. A
longof1234567can appear as1,234,567, which is a problem when you search logs for an ID. Pass identifiers asString(for exampleString.valueOf(id)).
SLF4J calls toString() on its arguments and does no number formatting.
Exceptions need the right overload
In SLF4J, a Throwable in the last argument position, with no placeholder left for it, is logged with its stack trace. In System.Logger, the varargs overload log(Level, String, Object...) does not do this. A Throwable passed there is just another argument for MessageFormat. Use log(Level, String, Throwable) instead.
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class ExceptionOverload {
private static final Logger LOG = System.getLogger(ExceptionOverload.class.getName());
public static void main(String[] args) {
try {
Integer.parseInt("not a number");
} catch (NumberFormatException e) {
LOG.log(Level.ERROR, "Parse failed", e); // stack trace recorded
}
}
}Best practices for log statements
Pass arguments instead of concatenating
Concatenation builds the string even when the level is disabled. Placeholders defer the formatting until the logger knows the message will be written.
log.debug("Loaded {} rows for tenant {}", rowCount, tenantId); // good
log.debug("Loaded " + rowCount + " rows for tenant " + tenantId); // wastefulSkip work only when the work itself is expensive
Placeholders defer formatting, but the arguments are still evaluated. If computing an argument is costly, such as serializing an object or running a query, defer it.
- In
System.Logger, use theSupplier<String>overload, or guard withisLoggable(Level.DEBUG). - In SLF4J, use
log.atDebug().log(() -> ...), or guard withisDebugEnabled().
Do not guard cheap calls. if (log.isDebugEnabled()) around a statement that only passes two variables adds noise and no speed.
Log an exception once, with its stack trace
The usual failure is logging at every layer. The same stack trace then appears three times and hides the real number of failures.
- Handle the exception where you can act on it (retry, return an error response, skip the record), and log it there.
- If you cannot handle it, let it propagate without logging. Wrap it with context if needed, and keep the original as the cause.
- Do not write
log.error(e.getMessage()). It loses the stack trace and the cause chain.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ImportService {
private static final Logger log = LoggerFactory.getLogger(ImportService.class);
public void importFile(String name) {
try {
parse(name);
} catch (IllegalArgumentException e) {
// Handled here: log once, with the exception as the last argument.
log.warn("Skipping file {}", name, e);
}
}
private void parse(String name) {
if (name.isEmpty()) {
throw new IllegalArgumentException("File name is empty");
}
}
}Keep secrets and personal data out of logs
Logs are copied to aggregators, tickets and chat. Treat them as less protected than your database.
- Never log passwords, tokens, API keys, full card numbers or session cookies.
- Be careful with
log.info("Request: {}", request). AtoString()that includes a header or body can leak data. Log selected fields. - Mask identifiers when full values are not needed, for example the last four digits.
- Do not rely on the log level to hide sensitive data. A
DEBUGstatement gets switched on in production during an incident.
Choose levels by who must act
Use the level to answer the question "does someone need to look at this?"
ERROR: an operation failed and someone may need to act.WARN(WARNINGinSystem.Logger): something unexpected happened, but the operation continued.INFO: significant lifecycle events, such as startup or a completed batch. A busy service should not write anINFOline for every request detail.DEBUGandTRACE: diagnostic detail for developers, off by default in production.
A validation failure caused by bad user input is normally not an ERROR. Otherwise your error alerts fire on user typos.
Write messages that stand alone
A line such as "Failed" is useless in an aggregator. Say what was attempted and for which entity: "Charge failed for customer {}". Keep the message text constant and put the variable parts in arguments or key-value pairs, so identical events are easy to group.
Add context once, not on every line
Instead of repeating the request ID in every message, put it in the MDC at the entry point and print it with %X{requestId} in the pattern. Always remove it afterwards. MDC.putCloseable in a try-with-resources block does that for you.
The next class combines these habits. It needs slf4j-api and logback-classic on the classpath, with a pattern that includes %X{requestId}.
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
public class InvoiceJob {
private static final Logger log = LoggerFactory.getLogger(InvoiceJob.class);
public static void main(String[] args) {
new InvoiceJob().run("req-1001", "alice", List.of("A1", "B2"));
new InvoiceJob().run("req-1002", "bob", List.of());
}
public void run(String requestId, String user, List<String> lines) {
try (MDC.MDCCloseable ignored = MDC.putCloseable("requestId", requestId)) {
log.info("Starting invoice run for user {} with {} lines", user, lines.size());
log.atDebug().log(() -> "Line detail: " + String.join(",", lines));
try {
bill(lines);
} catch (IllegalStateException e) {
log.error("Invoice run failed for user {}", user, e);
}
}
}
private void bill(List<String> lines) {
if (lines.isEmpty()) {
throw new IllegalStateException("Nothing to bill");
}
}
}The INFO line carries no secrets, the expensive DEBUG detail is built only when DEBUG is on, and the exception is logged once, at the point where the job decides to stop.
Common failure modes
| Symptom | Likely cause | Fix |
|---|---|---|
| Startup message that SLF4J defaulted to a no-operation implementation, and no log output | No SLF4J provider on the runtime classpath | Add a provider such as `logback-classic` |
| Warning about multiple providers | Two providers, for example Logback and `slf4j-simple`, both on the classpath | Keep one provider and exclude the other |
| `System.Logger` output ignores your Logback file | Bridge is missing, so the JDK default backend is used | Add `slf4j-jdk-platform-logging` at runtime |
| Argument missing from `System.Logger` output | `{}` used instead of `{0}` | Switch to indexed placeholders |
| `requestId` blank or wrong in some lines | MDC value not set, or set on a different thread | Set it where the work runs, and clear it afterward |
| Log file grows with repeated stack traces | Exception logged at several layers | Log once, where it is handled |
MDC and threads
MDC values live in a thread-local map. A task handed to an executor runs on another thread, which does not see the caller's values. Capture the value before submitting, and set it inside the task. Pooled threads are reused, so a value you never remove can leak into an unrelated request. This is the main reason to prefer putCloseable or a finally block with MDC.remove.
Logging in hot paths
A statement inside a tight loop is cheap when disabled, but it is not free. Each call still checks the level, and a per-iteration INFO line can produce millions of lines. Log a summary after the loop, or sample.
A short checklist
- Choose one API per codebase, based on dependency constraints and the need for MDC or key-value fields.
- Use that API's own placeholder syntax and exception overload.
- Add one provider (or one bridge plus one provider) to the runtime classpath of the application, not to libraries.
- Pick the level by who must act.
- Log each failure once, with its stack trace.
- Keep secrets out of messages and
toString()output. - Set context in MDC at the entry point and clear it.
Exercise
A library written with System.Logger contains the call LOG.log(Level.ERROR, "Save failed for {0}", id, e), where id is a String and e is a caught exception. The stack trace never appears in the application's Logback output. Why, and how do you fix it?
Show answer
The varargs overload log(Level, String, Object...) passes e to MessageFormat as an ordinary argument, so it is not recorded as an exception (and no placeholder consumes it). Put the identifier in the message and use the Throwable overload, for example LOG.log(Level.ERROR, "Save failed for " + id, e). Alternatively, log the identifier in one call and the exception in another only if you accept two lines. Also confirm slf4j-jdk-platform-logging is on the classpath, so the output reaches Logback at all.
Exercise
A service logs a caught exception in a repository class, rethrows it, logs it again in the service class, and logs it a third time in the web controller. Operations sees three ERROR entries per failed request. What change fixes this, and where should the single log statement go?
Show answer
Keep one log statement, at the point where the exception is actually handled, which here is the controller that turns it into an error response. The repository and service should let the exception propagate, or wrap it with added context and the original as the cause, without logging it. The controller then logs it once with the stack trace, for example log.error("Request failed for {}", requestId, e).
Exercise
You are writing a small command-line tool that needs per-run request identifiers on every log line, and you also want key-value fields on some events. Which API do you choose, and which two things must be on the runtime classpath?
Show answer
Choose SLF4J, because MDC and the fluent key-value API are not available in System.Logger. The runtime classpath needs slf4j-api and one provider, such as logback-classic. If you also want JDK and library System.Logger output to follow the same configuration, add slf4j-jdk-platform-logging as well.