Sub topic 5
Logging with SLF4J
This chapter assumes you can add a Maven or Gradle dependency, write a class with a static field, and use try/catch. You should also have read the previous chapters on log levels and System.Logger. This chapter covers the SLF4J API: the Logger type, how LoggerFactory hands out loggers, and how the five levels map onto methods. Message formatting, exceptions, providers, Logback configuration, MDC and the fluent API each get their own chapter, so they appear here only in passing.
What SLF4J is
SLF4J (Simple Logging Facade for Java) is a small library of interfaces. Your code calls org.slf4j.Logger, and a separate provider (also called a binding) does the real work of formatting and writing. This is the same idea as System.Logger. The difference is that SLF4J is a library you add as a dependency, while System.Logger ships with the JDK.
SLF4J is widely used. Many third-party libraries log through it, so using it in your application lets their output share your configuration.
Two artifacts are involved:
| Artifact | Role | Scope |
|---|---|---|
| `slf4j-api` | Interfaces your code compiles against: `Logger`, `LoggerFactory`, `MDC` | compile |
| A provider, such as `logback-classic` | Implements the logging at runtime | runtime |
The dependency block from the topic plan declares this split. Logback pulls in slf4j-api transitively, but listing it explicitly makes the compile-time dependency visible.
<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>Because the provider has runtime scope, nothing in your source can import ch.qos.logback classes by accident. Switching backends later means changing one dependency and no Java code.
Getting a logger
You obtain a logger from LoggerFactory. The standard idiom is one private static final field per class, named after the class:
package com.example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Greeter {
private static final Logger log = LoggerFactory.getLogger(Greeter.class);
public static void main(String[] args) {
log.trace("Entering main");
log.debug("Arguments received: {}", args.length);
log.info("Greeter started");
log.warn("No name given, using default");
log.error("Example error message");
}
}With only Logback on the classpath and no configuration file, Logback applies a default configuration. It writes to the console and enables DEBUG and above. The output looks like this, with your own timestamps:
06:41:18.815 [main] DEBUG com.example.Greeter - Arguments received: 0
06:41:18.817 [main] INFO com.example.Greeter - Greeter started
06:41:18.817 [main] WARN com.example.Greeter - No name given, using default
06:41:18.817 [main] ERROR com.example.Greeter - Example error messageThe TRACE line is missing because the default threshold is DEBUG. The next chapters show how to change that.
Why `static final`
Looking up a logger costs a map lookup by name. Doing that once per class at load time avoids repeating it on every call. A static logger is also shared by all instances, so you don't need a new field per object. The final modifier prevents accidental reassignment.
Logger names
getLogger(Class) is shorthand for getLogger(clazz.getName()). The name matters because backends build a hierarchy from dotted names. A logger named com.example.payments.PaymentService is a child of com.example.payments, which is a child of com.example, and so on up to the root logger. Configuring a level on a package applies to every logger below it.
You can also pass any string:
Logger audit = LoggerFactory.getLogger("audit");A custom name such as audit is useful when you want a category that cuts across classes, for example to send audit events to a separate file. Calling getLogger twice with the same name gives you the same logger instance in Logback. Do not rely on identity comparisons in your own code, though. The API only promises a logger with that name.
Copy-paste safety
A common bug is copying a logger line from another class and leaving the old class name in it. The log output then claims to come from the wrong class. If this bites your team, a form that cannot go stale is:
private static final Logger log =
LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());This needs import java.lang.invoke.MethodHandles;. Many teams instead generate the field with Lombok's @Slf4j or with an IDE template. Any of these approaches works. Pick one and apply it consistently.
Levels and methods
SLF4J has five levels, and each has a method with the same name in lowercase:
| SLF4J method | Level check | `System.Logger` level |
|---|---|---|
| `trace(...)` | `isTraceEnabled()` | `TRACE` |
| `debug(...)` | `isDebugEnabled()` | `DEBUG` |
| `info(...)` | `isInfoEnabled()` | `INFO` |
| `warn(...)` | `isWarnEnabled()` | `WARNING` |
| `error(...)` | `isErrorEnabled()` | `ERROR` |
Two differences from System.Logger are worth remembering:
- SLF4J has no
ALLorOFFlevel on theLoggerinterface. Those are configuration concepts that live in the backend. - SLF4J says
WARNandSystem.LoggersaysWARNING. If you move code between the two APIs, this is the one name that changes.
There is also no FATAL level. Use error for failures, and let the backend or your monitoring decide which errors page someone.
The method style differs from System.Logger, where one log method takes a Level argument. In SLF4J the level is part of the method name. This lets each method have overloads tuned for its common use.
The overloads
Each level method comes in several forms. Using info as the example:
log.info("Plain message");
log.info("One argument: {}", value);
log.info("Two arguments: {} and {}", a, b);
log.info("Many arguments: {} {} {}", a, b, c);
log.info("Something failed", exception);The {} placeholder mechanism and the rules for the trailing exception are covered in the next two chapters. The point here is that the overloads exist, so you rarely need to build strings with +.
Guarding expensive calls
When you pass arguments to a log method, Java evaluates them before the call, even if the level is disabled. Placeholders avoid the cost of string concatenation, but they do not avoid the cost of computing an argument. If computing the argument is expensive, check the level first:
if (log.isDebugEnabled()) {
log.debug("Cache contents: {}", cache.describeAllEntries());
}Without the guard, describeAllEntries() runs on every call, even when DEBUG is off. For cheap arguments such as a field read or an int, the guard only adds noise. SLF4J 2.x also offers lazy forms through the fluent API, covered in a later chapter.
A complete service example
This class uses the typical pattern of logging one line at the start of an operation and one when it fails:
package com.example;
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");
}
}
public static void main(String[] args) {
PaymentService service = new PaymentService();
service.charge("c-100", 2500);
service.charge("c-101", 0);
}
}The first call logs one INFO line. The second logs an INFO line, then an ERROR line followed by the stack trace of the IllegalStateException. The exception is the last argument and has no {} of its own, so SLF4J treats it as the exception to print.
Version and provider pitfalls
Most problems with SLF4J come from the classpath and not from your code.
No provider on the classpath
If only slf4j-api is present, SLF4J 2.x prints a warning to standard error at startup. It then discards every log call:
SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementationYour program keeps running, but nothing is logged. If logs vanish, check standard error for this message first. The next chapter explains how providers are located.
Mismatched versions
SLF4J 1.7.x and 2.x find their backends in different ways. Pair slf4j-api 2.x with Logback 1.3 or newer, and slf4j-api 1.7.x with Logback 1.2.x. A mismatch usually shows up as a message that a provider or binding was found for the wrong version, or as no output at all.
More than one provider
If two providers are present, for example Logback and slf4j-simple, SLF4J lists them, picks one, and warns about the choice. Remove the one you do not want. Do this in the build file, not in code.
Do not log through the provider directly
Code that imports ch.qos.logback.classic.Logger ties your class to one backend. Keep all import lines for logging limited to org.slf4j. The one exception is test or configuration code that deliberately manipulates the backend.
Summary
- Call
LoggerFactory.getLogger(Class)once per class and store the result in aprivate static final Logger. - The logger name decides which configuration applies, because names form a dotted hierarchy.
- SLF4J has
trace,debug,info,warnanderrormethods.System.LoggerusesWARNINGwhere SLF4J usesWARN. - Guard arguments that are expensive to compute with
isXxxEnabled(). - Compile against
slf4j-apionly, and supply a provider at runtime. A missing provider means silent NOP logging.
Exercise
A teammate copies the Greeter class to create Farewell, but forgets to change LoggerFactory.getLogger(Greeter.class). The logging output for Farewell is still written. What is wrong with it, and why does it matter when a package-level level is configured?
Show answer
Every line from Farewell is labelled with the logger name com.example.Greeter. Backends apply levels by logger name, so a level configured for Farewell's own name, or for a package that differs from Greeter's package, will not affect these messages. Readers of the log will also be misled about where each message came from. The fix is to call getLogger(Farewell.class), or to use MethodHandles.lookup().lookupClass() so the name cannot go stale.
Exercise
Your application has only slf4j-api 2.0.16 as a dependency and prints "SLF4J: No SLF4J providers were found." No log lines appear. Name a change to the build that fixes it, and say what scope the new dependency should have.
Show answer
Add a provider such as ch.qos.logback:logback-classic:1.5.12. It should have runtime scope, because application code compiles against slf4j-api only and never needs to reference Logback classes directly.