Sub topic 5
Logging with SLF4J
This chapter assumes basic Java syntax, classes, exceptions, and Maven or Gradle dependency management. It also assumes that you know what a log level is: a label such as INFO, DEBUG, or ERROR that describes the importance of a log event.
Why use SLF4J?
SLF4J, or Simple Logging Facade for Java, is an API for writing log messages without choosing the logging implementation in application code. Your code calls SLF4J. A separate provider, such as Logback, writes the messages to a console, file, or log service.
This separation is useful when different applications need different logging configurations. A library can depend on slf4j-api without forcing its users to use a particular backend.
The application usually depends on the API at compile time and a provider at runtime:
| Dependency | Purpose | Typical scope |
|---|---|---|
| `slf4j-api` | Provides `Logger` and `LoggerFactory` | Compile and runtime |
| `logback-classic` | Implements SLF4J logging | Runtime |
For Maven, the dependencies can look like this:
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.16</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.12</version>
<scope>runtime</scope>
</dependency>
</dependencies>Creating and using a logger
Create one logger for each class. LoggerFactory.getLogger uses the class name as the logger name. Backends can then configure levels by package or class.
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) {
log.info("Charging customer {} amount {} cents",
customerId, amountCents);
if (amountCents <= 0) {
log.warn("Rejected non-positive charge for customer {}",
customerId);
return;
}
log.debug("Charge passed validation for customer {}",
customerId);
}
public static void main(String[] args) {
new PaymentService().charge("customer-42", 1250);
}
}SLF4J replaces each {} placeholder with the next argument. The placeholders keep formatting separate from the message text and allow the provider to avoid some work when a level is disabled.
Common methods include:
trace: extremely detailed diagnostic information.debug: information useful while diagnosing a problem.info: normal application progress.warn: an unusual condition that does not stop the operation.error: an operation failed or requires attention.
Provider selection
SLF4J 2.x discovers a provider at runtime through Java’s service-provider mechanism. If no provider is present, SLF4J prints a warning and uses a no-operation implementation. Your application still starts, but its log messages are discarded.
If several providers are present, SLF4J reports a multiple-provider warning and selects one. Treat that warning as a dependency configuration error. Keep one intended provider on the runtime classpath.
Logging exceptions
Pass an exception as the final argument when you want its stack trace recorded:
try {
chargeAccount(customerId);
} catch (IllegalStateException e) {
log.error("Charge failed for customer {}", customerId, e);
}The exception does not consume a {} placeholder in this form. The output contains the customer identifier, the error message, and the full stack trace.
What to remember
SLF4J defines the logging calls, while a provider defines their destination and formatting. Use parameterized messages with {}. Choose the lowest useful amount of detail, attach exceptions as the final argument, and verify that exactly one provider is available at runtime.
Exercise
What is wrong with log.debug("User data: " + loadUserData()), and how could you improve it?
Show answer
The method call and string construction happen even when DEBUG logging is disabled. Avoid logging sensitive data, and use a parameterized message such as log.debug("Loaded user {}", userId). For expensive diagnostic work, check log.isDebugEnabled() before computing the value.