Sub topic 2
Logging with SLF4J
This chapter assumes basic Java, try/catch, and Maven or Gradle dependency management. SLF4J is a logging facade: an API that lets application code write logs without depending directly on a logging backend. A backend, such as Logback, formats and writes those logs.
Logging with SLF4J
Create a logger for the class with LoggerFactory. Use levels according to the importance of an event:
DEBUGrecords details useful during diagnosis.INFOrecords normal, important application events.WARNrecords a recoverable problem.ERRORrecords a failed operation.
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);
try {
process(customerId, amountCents);
} catch (IllegalStateException e) {
log.error("Charge failed for customer {}", customerId, e);
}
}
private void process(String customerId, long amountCents) {
if (amountCents <= 0) {
throw new IllegalStateException("Amount must be positive");
}
}
}Parameterized messages and avoiding wasted work
SLF4J replaces each {} with the next argument. This avoids building a string when the selected level is disabled.
log.debug("Loaded customer {} with {} orders", customerId, orderCount);Avoid concatenation for expensive or unnecessary values:
// The method runs even when DEBUG is disabled.
log.debug("State: " + buildDetailedState());For SLF4J 2.x, the fluent API can defer work and attach named fields:
log.atInfo()
.addKeyValue("customerId", customerId)
.log("Customer loaded");Logging exceptions correctly
Pass the exception as the final argument when the last placeholder has no matching value. SLF4J then records its message and stack trace.
log.error("Charge failed for customer {}", customerId, exception);Use a separate placeholder only when you intentionally want the exception text as a field. Logging only exception.getMessage() loses the stack trace and makes diagnosis harder.
SLF4J providers and the missing-provider warning
SLF4J defines the API, but a provider performs the actual output. Add slf4j-api for compilation and one provider, such as Logback, at runtime.
<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>If no provider is available, SLF4J 2.x prints a warning and uses a no-operation implementation. Your application continues running, but its logs are discarded. If multiple incompatible providers are present, SLF4J reports the conflict; remove unintended providers.
Exercise
What happens to an exception's stack trace when you call log.error("Failed: {}", e.getMessage()) instead of passing e as the final argument?
Show answer
Only the exception message is logged. Pass e as the final argument to record the stack trace.