Sub topic 12
Routing System.Logger into SLF4J
This chapter assumes you have read the earlier chapters on System.Logger, how the JDK finds its backend, SLF4J and Logback configuration. You should be comfortable adding Maven dependencies and reading a logback.xml file.
The problem: two logging systems in one process
A typical application has several sources of log output:
- Your own code, which may call SLF4J.
- Libraries that call
System.getLogger, because they target Java 9 or later and do not want a logging dependency. - JDK classes that log through
System.Logger, such as thejava.net.httpclient.
By default, System.Logger output goes to the backend the JDK picks. When java.logging is present, that backend is java.util.logging (JUL). Your SLF4J calls go to Logback. The result is two configurations, two output formats and two sets of level rules. A line logged by a library may appear on stderr in the JUL format, while your own lines follow your Logback pattern.
The fix is to register an SLF4J-aware System.LoggerFinder. Then every System.Logger call is handed to SLF4J, and from there to whichever provider you installed.
The bridge module
The artifact org.slf4j:slf4j-jdk-platform-logging contains a System.LoggerFinder implementation. Its job is to produce System.Logger objects that delegate to an SLF4J Logger of the same name.
Add it next to your SLF4J provider. Keep all SLF4J artifacts on the same version.
<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>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk-platform-logging</artifactId>
<version>2.0.16</version>
<scope>runtime</scope>
</dependency>
</dependencies>No code changes are needed. The jar registers itself in two ways:
- On the classpath, through a
META-INF/services/java.lang.System$LoggerFinderfile. - On the module path, through a
provides java.lang.System.LoggerFinder with ...declaration in itsmodule-info. The module name isorg.slf4j.jdk.platform.logging.
System.getLogger locates the finder with ServiceLoader, so the jar only has to be present at runtime.
A runnable demonstration
This class logs through System.Logger only. It has no SLF4J import.
package com.example;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class BridgeDemo {
private static final Logger LOG = System.getLogger(BridgeDemo.class.getName());
public static void main(String[] args) {
LOG.log(Level.INFO, "Starting with {0} arguments", args.length);
LOG.log(Level.DEBUG, () -> "Debug detail for " + BridgeDemo.class.getSimpleName());
LOG.log(Level.WARNING, "Disk usage at {0}%", 91);
LOG.log(Level.ERROR, "Something failed", new IllegalStateException("demo"));
}
}Use this logback.xml in src/main/resources:
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.example" level="DEBUG"/>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>Run it with the bridge on the classpath. The output follows the Logback pattern, and the DEBUG line appears because the com.example logger is set to DEBUG:
06:37:55.801 INFO [main] com.example.BridgeDemo - Starting with 0 arguments
06:37:55.803 DEBUG [main] com.example.BridgeDemo - Debug detail for BridgeDemo
06:37:55.803 WARN [main] com.example.BridgeDemo - Disk usage at 91%
06:37:55.804 ERROR [main] com.example.BridgeDemo - Something failed
java.lang.IllegalStateException: demo
at com.example.BridgeDemo.main(BridgeDemo.java:13)Remove the bridge dependency and run again. The same calls now print through JUL's SimpleFormatter on stderr, only at INFO and above, and the logback.xml levels no longer apply. That difference is the quickest way to confirm the bridge is active.
What the bridge does to each call
The bridge's System.Logger implementation does three things for every call.
Level mapping
The two APIs share most level names but not all of them.
| System.Logger level | SLF4J level |
|---|---|
| `TRACE` | `TRACE` |
| `DEBUG` | `DEBUG` |
| `INFO` | `INFO` |
| `WARNING` | `WARN` |
| `ERROR` | `ERROR` |
Level.ALL and Level.OFF are filtering thresholds rather than levels you would normally log at, so avoid logging with them.
isLoggable(Level) on the bridged logger asks the SLF4J logger whether that level is enabled. Your Logback configuration therefore decides what isLoggable returns, and the Supplier overload of log is skipped when the level is disabled.
Logger names
System.getLogger("com.acme.Client") becomes LoggerFactory.getLogger("com.acme.Client"). Per-package levels in logback.xml apply to library code exactly as they do to yours. To quiet a chatty library, name its package:
<logger name="com.acme.client" level="WARN"/>Message formatting
System.Logger uses java.text.MessageFormat syntax with {0}, {1} and so on. SLF4J uses {}. The bridge formats System.Logger messages itself with MessageFormat before handing the text to SLF4J. So {0} in a library message works, and you do not rewrite those messages as {}.
When a message has no parameters, the bridge does not run it through MessageFormat. An apostrophe in such a message is therefore not treated as a quote character. With parameters, MessageFormat rules apply, so a literal ' or { needs escaping.
If a call passes a resource bundle, the message is first used as a key and looked up in the bundle. This is the System.Logger localization feature, and it still works through the bridge.
Loading rules and edge cases
Only one finder is used
System.LoggerFinder is a single-instance service. If several jars register a finder, ServiceLoader returns one of them, and the JDK throws an error if loading a finder fails. Do not combine slf4j-jdk-platform-logging with another bridge such as Log4j's log4j-jpl. Choose one.
Bootstrap logging
Some JDK code logs before the finder has been found. The JDK holds those early messages in a bootstrap logger and later redirects it to the real finder. A few very early startup messages can still go to the default destination.
Timing
The finder is located the first time something requests a System.Logger. It is cached after that. Adding the dependency to the classpath is enough, but changing it at runtime has no effect.
The provider must exist
The bridge delegates to SLF4J, so it needs an SLF4J provider. With the bridge but no provider, you get the SLF4J "no providers were found" warning, and all output, including from System.Logger, is discarded. Install a provider such as logback-classic.
Modules
On the module path, the bridge module must be resolved. Resolution does not happen on its own, because nothing in your code names it. Add it to the module graph with --add-modules org.slf4j.jdk.platform.logging. Alternatively, build a custom runtime with jlink --add-modules and --bind-services.
Checking that the bridge is active
Use these checks, in order of effort:
- Log with
System.Loggerand look for your Logback pattern in the output. - Print the finder class at startup:
public class WhichFinder {
public static void main(String[] args) {
System.out.println(System.LoggerFinder.getLoggerFinder().getClass().getName());
}
}With the bridge present, the printed class lives in the org.slf4j.jdk.platform.logging package. Without it, you see a JDK internal class name. Note that getLoggerFinder() checks a LoggingPermission("loggerFinder") permission when a SecurityManager is installed. Normal applications are unaffected.
- Set
<configuration debug="true">inlogback.xml. Logback prints its configuration steps, which confirms which file was loaded.
Performance
The bridge adds one extra layer per call: a MessageFormat pass when parameters are given, then the SLF4J call. For most applications this cost is negligible. Two habits keep it low:
- Pass parameters rather than concatenating strings, so a disabled level skips the formatting.
- Use the
Supplieroverload for values that are expensive to build. The supplier runs only if the level is enabled.
Summary of the setup
- Choose an SLF4J provider, for example Logback, and configure it.
- Add
slf4j-jdk-platform-loggingat runtime with the same version asslf4j-api. - Confirm with the finder check or by comparing output with and without the bridge.
- Tune library noise using ordinary logger names in
logback.xml.
Exercise
A library in your application calls System.getLogger("com.acme.client").log(Level.DEBUG, "Retry {0}", 2). Your logback.xml sets the root level to INFO and has no entry for com.acme. You have slf4j-api, logback-classic and slf4j-jdk-platform-logging on the classpath. Does the line appear? What single change makes it appear, without changing the library or the root level?
Show answer
It does not appear. The bridge maps DEBUG to SLF4J DEBUG, and the logger com.acme.client inherits the INFO root level, so the call is filtered out. Add <logger name="com.acme.client" level="DEBUG"/> (or com.acme) to logback.xml.
Exercise
After adding slf4j-jdk-platform-logging, your library messages still print in the default JUL format on stderr. List two likely causes.
Show answer
Any two of: the dependency is not on the runtime classpath (for example it is declared with the wrong scope or in the wrong module); on the module path, the org.slf4j.jdk.platform.logging module is not resolved because nothing requires it and --add-modules was not given; another System.LoggerFinder provider is registered and was chosen instead; the SLF4J jar versions are mixed so the bridge fails to load.
Exercise
A message logged through System.Logger is "User {0} logged in" with the argument "ana". What text reaches Logback, and why do you not need to change the placeholder to {}?
Show answer
The text is User ana logged in. The bridge formats System.Logger messages with MessageFormat before passing them on, so {0} placeholders are resolved by the bridge and SLF4J receives the finished string.