What SLF4J dependency rule would you set for every library and service in an organisation, and how would you make the build enforce it?
answer
- facade for libraries, choice for apps
- exactly one provider at runtime
- no 1.7-era binders left
- SLF4J only warns, never fails
- fail the build, alert at boot
basics
~20 sLibraries depend on slf4j-api only; each application ships exactly one provider at runtime scope and no 1.7-era binding. Because SLF4J merely warns or goes silent, a build check counting providers and StaticLoggerBinder resources must enforce it.
solid answer
~40 sThe rule: libraries declare only `slf4j-api` (any provider they need for their own tests stays in test scope), and every application declares exactly one provider at runtime scope, with no 1.7-era binding and one `slf4j-api` version. It needs enforcing because SLF4J never fails: two providers produce a warning and an arbitrary winner, none produces a silent no-op logger. I would publish one shared check that every application's build runs: count `SLF4JServiceProvider` registrations with `ServiceLoader`, require zero `org/slf4j/impl/StaticLoggerBinder.class` resources, and assert the factory is not `NOPLoggerFactory`, plus build-tool bans on known duplicates. The judgment calls are rolling it out as a warning before it becomes an error, failing builds rather than boots, and recording explicit exceptions for plugin hosts.
code
java · 39 linesimport static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.ServiceLoader;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.NOPLoggerFactory;
import org.slf4j.spi.SLF4JServiceProvider;
class LoggingClasspathTest {
private final ClassLoader loader = LoggerFactory.class.getClassLoader();
@Test
void exactlyOneSlf4jProvider() {
List<String> providers = ServiceLoader.load(SLF4JServiceProvider.class, loader)
.stream()
.map(p -> p.type().getName())
.collect(Collectors.toList());
assertEquals(1, providers.size(), "SLF4J providers on the classpath: " + providers);
}
@Test
void noSlf4j17Bindings() throws Exception {
List<URL> bindings = Collections.list(loader.getResources("org/slf4j/impl/StaticLoggerBinder.class"));
assertTrue(bindings.isEmpty(), "1.7-era SLF4J bindings: " + bindings);
}
@Test
void notBoundToNoOpLogger() {
assertFalse(LoggerFactory.getILoggerFactory() instanceof NOPLoggerFactory,
"SLF4J is discarding every log call");
}
}go deeper
Recall that a library depends on slf4j-api only and that the application chooses the one backend.
Explain why SLF4J cannot enforce this itself: two providers give a warning and the first one wins, none gives a silent no-op logger.
Show how to detect each failure mechanically: provider registrations through ServiceLoader, StaticLoggerBinder resources for 1.7 bindings, and the NOPLoggerFactory outcome.
Own the rollout trade-offs: strict build versus lenient boot, a warning period before enforcement, explicit exceptions, and who maintains the shared check.
## The decision a lead has to make SLF4J leaves the choice of backend to whoever assembles the final classpath, and it is forgiving about mistakes: with **no** provider it silently discards every log call, and with **several** it prints a warning and binds whichever one `ServiceLoader` returns first. Neither case stops a build or a deployment. Across many services and shared libraries that forgiveness turns into incidents, so a lead has to decide two things: **what the rule is**, and **where it is enforced**. ## The rule most teams converge on 1. **Libraries depend on `slf4j-api` only.** A reusable library compiles against the facade and never brings a provider into its consumers' classpath. If its own tests need output, a provider such as `slf4j-simple` or `slf4j-nop` goes in **test scope only**. 2. **Each application carries exactly one provider**, declared by the application itself and needed only at **runtime** (Maven's `runtime` scope, Gradle's `runtimeOnly`), because application code compiles against `slf4j-api` and never against the provider. 3. **No 1.7-era bindings** anywhere on a 2.0 classpath: nothing that ships `org/slf4j/impl/StaticLoggerBinder.class`, since the 2.0 API never binds to it. 4. **One `slf4j-api` version per application**, kept in step with the provider's version. 5. Bridges that reroute legacy logging APIs are allowed, but they follow their own pairing rules, covered with the legacy bridges. Rules 1 and 2 split responsibility cleanly: library authors cannot pick the backend for everyone, and application owners cannot blame a library for doubled or missing output. ## Where to enforce it, and what each place costs | Enforcement point | Catches | Cost and blind spots | |---|---|---| | Build-tool rules (banned dependencies, capability conflicts) | known provider artifacts before packaging | needs a maintained list; misses providers repackaged under other coordinates | | A classpath test in each application | any `SLF4JServiceProvider` registration or `StaticLoggerBinder` resource, whatever its jar | sees the **test** classpath, which can differ from runtime | | A startup self-check | the classpath that really ships | finds the problem only at deploy time, and must not take a healthy service down for a logging issue | | SLF4J's own `SLF4J(W):` lines | everything, at runtime | only a warning on stderr; nobody is obliged to read it | The build-tool mechanics (exclusions, banned dependencies, capability resolution) belong to the Maven and Gradle dependency-management material. What SLF4J itself contributes is a **reliable signature** to check for: - a 2.0 provider is a `META-INF/services/org.slf4j.spi.SLF4JServiceProvider` registration, which `ServiceLoader` can enumerate without instantiating anything; - a 1.7 binding is a `org/slf4j/impl/StaticLoggerBinder.class` resource; - a NOP outcome shows up as `LoggerFactory.getILoggerFactory()` returning a `NOPLoggerFactory`. A shared test, published once and run by every application's build, turns those three facts into a gate. The test classpath includes runtime dependencies plus test-only ones, so an application that also adds a test-scoped provider fails the check; most teams accept that as a feature, because it forces one provider everywhere. ## The judgment calls - **Fail the build, warn at boot.** A build failure costs a developer minutes; a boot failure over logging costs an outage. Most leads make the build strict and the runtime check an alert. - **Strictness versus migration cost.** Turning the rule on across many services at once breaks many builds. Rolling it out as a warning first, with a date for it to become an error, is usually cheaper than a flag day. - **Exceptions are explicit.** Plugin hosts, application servers and test harnesses sometimes need two providers or the `slf4j.provider` override. Allow them with a named owner and a recorded reason rather than weakening the rule for everyone. - **Who owns the shared check.** A platform or build team that publishes the test keeps the signatures current when SLF4J changes again, which happened once already between 1.7 and 2.0. ## Why it is worth a rule The failure mode is silence: logs that stop after a routine upgrade, or a backend that changes because dependency order changed. Neither shows up in functional tests. A single rule, checked mechanically, removes the whole class of incident for the price of one shared test and a few exclusions.
- Why should a library never ship a provider at compile or runtime scope, even a harmless one like slf4j-simple?Every consumer would inherit it, so an application that adds its own backend now has two providers. SLF4J then warns and binds whichever `ServiceLoader` returns first, which depends on classpath order. The library has quietly taken a decision that belongs to the application. Test scope keeps the convenience without leaking it.
- When would you accept the slf4j.provider override instead of the one-provider rule?Only where the classpath is not yours to change: an application server or a vendor distribution that bundles two providers, or a test harness that must force one. Record the exception with an owner and a reason, because the override hides the duplicate and silently stops working if a launch omits the `-D` flag.
- A library should ship a default provider so it logs out of the box.
- SLF4J refuses to start with two providers, so no check is needed.
- Counting provider registrations also catches 1.7-era bindings.
- A startup check that kills the service is the best enforcement point.
- The slf4j.provider property makes duplicate providers harmless.
Assumes the SLF4J 2.0 line, where providers are SLF4JServiceProvider registrations and 1.7-era StaticLoggerBinder bindings are never used.