Sub topic 13
Choosing an API and Logging Best Practices
This chapter assumes basic Java classes, try/catch, Maven or Gradle dependencies, and the difference between an application and a library. Familiarity with Java modules helps, but it is not required.
Java applications commonly log through an API, or facade, instead of calling a concrete logging backend directly. A facade defines the calls your code makes. A backend decides where messages go and how they are formatted. This separation lets an application change from the JDK backend to Logback without rewriting every log statement.
Choosing between System.Logger and SLF4J
System.Logger is part of the JDK since Java 9. It is a good default when you want no logging dependency in a small application or library. It supports levels, formatted messages, lazy message suppliers, and exceptions.
SLF4J is a widely used facade with a larger ecosystem. It is often the practical choice when your application already uses Logback, when several libraries use SLF4J, or when you need features such as mapped diagnostic context (MDC) and structured key-value fields.
| Situation | Reasonable choice |
|---|---|
| A Java 9+ library with minimal dependencies | `System.Logger` |
| An application already using Logback | SLF4J |
| A service that needs MDC or fluent key-value logging | SLF4J |
| Code shared across many environments | Follow the surrounding project convention |
Do not use both APIs randomly in the same application. Pick one for application code unless you have a clear integration reason. A bridge can route System.Logger calls into SLF4J, allowing one backend configuration.
Use levels as a filtering policy
A log level communicates both importance and expected volume.
TRACErecords very detailed diagnostic state.DEBUGrecords information useful while investigating a problem.INFOrecords normal significant events, such as service startup or a completed operation.WARNINGrecords an unusual condition that did not necessarily stop the operation.ERRORrecords a failed operation or an error requiring attention.
System.Logger calls this level WARNING; SLF4J calls the equivalent level WARN. Avoid logging every method call at INFO. High-volume normal events make important failures harder to find.
Apply the same practices to either API
Use stable event descriptions and include identifiers that help an operator connect related events. Do not log passwords, access tokens, full payment details, or personal data unless your security and privacy rules explicitly allow it.
With System.Logger, use its formatting and supplier overloads:
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public final class Checkout {
private static final Logger LOG =
System.getLogger(Checkout.class.getName());
public static void main(String[] args) {
String orderId = "A-1042";
LOG.log(Level.INFO, "Starting checkout for order {0}", orderId);
if (LOG.isLoggable(Level.DEBUG)) {
LOG.log(Level.DEBUG, () -> "Diagnostic data: " + expensiveDetails());
}
try {
validate(orderId);
} catch (IllegalArgumentException exception) {
LOG.log(Level.ERROR, "Checkout rejected for order {0}",
exception);
}
}
private static void validate(String orderId) {
if (orderId.isBlank()) {
throw new IllegalArgumentException("Order id is empty");
}
}
private static String expensiveDetails() {
return "validation-state";
}
}The {0} placeholder uses MessageFormat-style arguments. A supplier delays string construction, but it does not make unsafe data safe. Check the level before doing expensive calculations when necessary.
With SLF4J, use {} placeholders and pass the exception separately:
log.error("Checkout failed for order {}", orderId, exception);If the exception is passed where a placeholder is expected, SLF4J may treat it as a normal value instead of recording its stack trace.
Keep one logging pipeline
A backend must be present at runtime. SLF4J application code usually depends on slf4j-api, while a provider such as Logback supplies the implementation. If no provider is present, SLF4J emits a warning and may discard messages.
Use one configured pipeline where possible:
For request-scoped data, SLF4J with MDC can attach a request ID to every message on the current thread. Always clear that data when work ends, especially in thread pools. For newer SLF4J versions, fluent calls such as log.atInfo().addKeyValue("orderId", id).log("Order accepted") provide structured fields, but the encoder must be configured to render them.
A practical decision rule
Start with the API already used by the project. For a new Java 9+ library, prefer System.Logger when dependency minimization matters. For a service with Logback, MDC, structured output, or an established SLF4J ecosystem, choose SLF4J. Whichever API you select, configure levels centrally, preserve exception causes, avoid expensive disabled-level work, and review logs as operational data.
Exercise
A service uses Logback, needs a request ID on every message, and already has several SLF4J dependencies. Which API should its application code use, and why?
Show answer
Use SLF4J because it matches the existing provider and supports MDC and fluent structured logging without introducing a second logging path.