Sub topic 4
How System.Logger finds its backend
This chapter assumes you can write a basic System.Logger call, as shown in the previous chapter. It also assumes you know the Java service-loading idea: a META-INF/services file or a provides clause in module-info.java names an implementation of an interface. You don't need to know the module system in depth.
System.Logger is only a front end. It has no code that writes text anywhere. Every System.getLogger(...) call is handed to a backend, and this chapter explains how the JDK picks it, how to see which one you got, and how to replace it.
The lookup in one picture
A call to System.getLogger(name) is routed through a System.LoggerFinder. This abstract class has one job: given a logger name and the module of the caller, return a System.Logger.
There are three outcomes:
| Situation | Backend you get | Configured with |
|---|---|---|
| A `LoggerFinder` provider is registered | Whatever the provider returns | The provider's own mechanism |
| No provider, `java.logging` is present (the normal case) | `java.util.logging` (JUL) | `logging.properties` or `-Djava.util.logging.config.file` |
| No provider, `java.logging` is absent | A minimal console logger | Not configurable. Output is INFO and above on `System.err`. |
The second row is why System.Logger works with no setup. Most people never see the lookup.
The default: java.util.logging
With no provider, each System.Logger forwards to a JUL logger of the same name. Levels are translated like this:
| System.Logger.Level | JUL level |
|---|---|
| `ALL` | `ALL` |
| `TRACE` | `FINER` |
| `DEBUG` | `FINE` |
| `INFO` | `INFO` |
| `WARNING` | `WARNING` |
| `ERROR` | `SEVERE` |
| `OFF` | `OFF` |
JUL's default root level is INFO, and its default ConsoleHandler writes to System.err. So a DEBUG call is silently dropped on a fresh JVM. This surprises many people, because the code looks right and the output is simply missing. To see debug output with the default backend, you must lower both the logger level and the handler level. Setting only one is not enough, because the ConsoleHandler has its own INFO threshold.
Here is a logging.properties that enables DEBUG for one logger name:
handlers=java.util.logging.ConsoleHandler
.level=INFO
java.util.logging.ConsoleHandler.level=ALL
com.example.level=FINEStart the JVM with -Djava.util.logging.config.file=logging.properties. The ConsoleHandler now lets everything through, and only com.example and its children produce FINE (that is, DEBUG) records.
Checking which backend you got
Do not guess. Print the classes involved:
package com.example;
public class WhichBackend {
public static void main(String[] args) {
System.Logger logger = System.getLogger("demo");
System.out.println("Logger class: " + logger.getClass().getName());
System.out.println("Finder class: "
+ System.LoggerFinder.getLoggerFinder().getClass().getName());
logger.log(System.Logger.Level.INFO, "Hello from {0}", "System.Logger");
logger.log(System.Logger.Level.DEBUG, "This line shows only if DEBUG is enabled");
}
}With no provider, the finder class is an internal JDK class and the logger class is an internal wrapper around JUL. The exact names depend on the JDK version, so don't hard-code them in tests. The INFO line appears on System.err with JUL's two-line format. The DEBUG line does not appear.
The JDK checks the loggerFinder runtime permission only when a security manager is installed, which is rare today. Without one, getLoggerFinder() works as shown.
Writing your own LoggerFinder
Write a custom finder when you want System.Logger calls to go to something JUL does not cover, such as a company-wide logging service. The most common reason is to forward to a library like SLF4J, and the next chapters cover a ready-made bridge for that. The steps for a custom finder are the same either way.
First, extend System.LoggerFinder and implement getLogger(String, Module). The System.Logger it returns must implement four members: getName(), isLoggable(Level), and two log methods. The Supplier overloads are default methods that call them.
package com.example.logging;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class ConsoleLoggerFinder extends System.LoggerFinder {
// Public no-argument constructor is required by ServiceLoader.
public ConsoleLoggerFinder() {
}
@Override
public System.Logger getLogger(String name, Module module) {
return new ConsoleLogger(name);
}
private static final class ConsoleLogger implements System.Logger {
private final String name;
ConsoleLogger(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isLoggable(Level level) {
// Show DEBUG and above. OFF is a threshold, not a message level.
return level != Level.OFF
&& level.getSeverity() >= Level.DEBUG.getSeverity();
}
@Override
public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) {
if (!isLoggable(level)) {
return;
}
System.out.println("[custom] " + level + " " + name + " - " + localize(bundle, msg));
if (thrown != null) {
thrown.printStackTrace(System.out);
}
}
@Override
public void log(Level level, ResourceBundle bundle, String format, Object... params) {
if (!isLoggable(level)) {
return;
}
String text = localize(bundle, format);
if (params != null && params.length > 0) {
text = MessageFormat.format(text, params);
}
System.out.println("[custom] " + level + " " + name + " - " + text);
}
private static String localize(ResourceBundle bundle, String key) {
if (bundle == null || key == null) {
return key;
}
try {
return bundle.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
}
}Second, register the class. On the class path, create a file whose name is the interface's binary name, java.lang.System$LoggerFinder, under META-INF/services:
com.example.logging.ConsoleLoggerFinderThe file path is src/main/resources/META-INF/services/java.lang.System$LoggerFinder. The $ is part of the file name. In a shell, quote it so the shell does not expand it.
In a named module, declare the provider in module-info.java instead:
module com.example.logging {
provides java.lang.System.LoggerFinder
with com.example.logging.ConsoleLoggerFinder;
}Run WhichBackend again with the provider on the class path. The finder class is now com.example.logging.ConsoleLoggerFinder, and the DEBUG line appears with the [custom] prefix. The JUL configuration no longer matters for these calls, because JUL is not involved.
Rules and failure modes
- System class loader only. The JDK loads the finder through the system (application) class loader. A provider inside a web application's own class loader, or one added by a plugin loader at runtime, is invisible to this lookup.
- One provider. The JDK expects a single
LoggerFinder. If two jars on the path both register one, you get aServiceConfigurationErrorinstead of a silent choice. Check for transitive dependencies that bring in their own finder. - Do not log from the finder itself. The finder is created while the first logger is being requested. Calling
System.getLoggerfrom its constructor or static initializer can recurse into the lookup and fail. Keep the constructor trivial and create any heavy resources lazily. - The module argument.
getLogger(name, module)receives the module of the code that calledSystem.getLogger. You can use it to apply different settings per module, but most finders ignore it. - Level checks belong in the logger.
isLoggableis called by theSupplieroverloads before the supplier runs. If yourisLoggablealways returnstrue, you lose the lazy evaluation that makes those overloads worth using.
Why this design matters
The JDK itself uses System.Logger for some platform logging. Because those calls go through the same finder as your application, replacing the finder redirects JDK output as well. This is what makes the bridge in a later chapter useful. One provider lets JDK messages, library messages and application messages share one configuration.
Without a provider, JDK output goes to JUL, while your application may send its own logs through SLF4J and Logback. Two backends then run side by side, each with its own configuration file and level settings. Seeing one half of the output in the format you set and the other half in JUL's default two-line format is the usual symptom.
Exercise
A team sets com.example.level=FINE in logging.properties and starts the JVM with -Djava.util.logging.config.file=logging.properties. Their code calls LOG.log(Level.DEBUG, "cache miss") on a System.Logger named com.example.Cache, and nothing is printed. No custom LoggerFinder is registered. What is the most likely cause, and how do they fix it?
Show answer
The default ConsoleHandler still has its own level of INFO, so it discards the FINE record even though the logger accepts it. Add java.util.logging.ConsoleHandler.level=ALL (or FINE) to the file, and make sure the file also lists handlers=java.util.logging.ConsoleHandler. DEBUG maps to FINE, so the logger level alone is not enough.
Exercise
You add a jar that registers its own System.LoggerFinder to an application that already has one from another jar. What happens, and what would you check first?
Show answer
The JDK expects a single finder, so startup or the first System.getLogger call fails with a ServiceConfigurationError instead of picking one. Look for META-INF/services/java.lang.System$LoggerFinder entries (and provides java.lang.System.LoggerFinder clauses) across your dependencies, and remove or exclude one of the providers.