Sub topic 3
Logging with System.Logger
This chapter assumes you know basic Java syntax, can use try/catch, and have read the earlier chapters on why applications log through a facade and how log levels are chosen. Module-system knowledge helps but is not required.
System.Logger is the logging facade built into the JDK since Java 9. It lives in java.base, so it needs no dependency and no requires directive. The JDK itself uses it internally. Application code and libraries that want to avoid third-party dependencies can use it too.
The shape of the API
System.Logger is an interface nested inside java.lang.System. You get an instance from a static factory and keep it in a constant:
private static final System.Logger LOG = System.getLogger(MyClass.class.getName());The string is the logger name. By convention it is the fully qualified class name. Backends use the name to apply per-package configuration, so avoid inventing ad hoc names.
There are two factory methods:
System.getLogger(String name)returns a logger for that name.System.getLogger(String name, ResourceBundle bundle)returns a logger that treats message strings as keys in the bundle, for localized messages.
The interface has only a few members. getName() returns the name. isLoggable(Level) tells you whether a level is currently enabled. The rest are overloads of log.
Levels
System.Logger.Level is an enum. Its values, from least to most severe, are:
| Level | Typical use |
|---|---|
| `ALL` | Configuration only: enable every message |
| `TRACE` | Very fine-grained flow and state |
| `DEBUG` | Diagnostic detail for developers |
| `INFO` | Normal, noteworthy events |
| `WARNING` | Something unexpected that the application handled |
| `ERROR` | An operation failed |
| `OFF` | Configuration only: disable everything |
ALL and OFF exist so a backend can express "everything" and "nothing" as thresholds. Do not log at those levels.
The name WARNING is different from SLF4J, which uses WARN. This is a common source of compile errors when you move code between the two APIs.
The log overloads
All log calls take a Level first. These are the overloads you will use most.
| Call | When to use it |
|---|---|
| `log(Level, String msg)` | A fixed message |
| `log(Level, String format, Object... params)` | A message with `{0}`, `{1}` placeholders |
| `log(Level, String msg, Throwable thrown)` | A message plus an exception |
| `log(Level, Supplier<String> msgSupplier)` | An expensive message built only if the level is enabled |
| `log(Level, Supplier<String>, Throwable)` | The same, with an exception |
| `log(Level, Object obj)` | Logs `obj.toString()` |
There are also variants that take a ResourceBundle after the level. They are used for localization and are rare in application code.
Here is a complete class that uses three of them:
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class OrderService {
private static final Logger LOG = System.getLogger(OrderService.class.getName());
public void place(String orderId) {
LOG.log(Level.INFO, "Placing order {0}", orderId);
try {
if (orderId.isBlank()) {
throw new IllegalArgumentException("Empty order id");
}
LOG.log(Level.DEBUG, () -> "Order " + orderId + " validated");
} catch (IllegalArgumentException e) {
LOG.log(Level.ERROR, "Could not place order", e);
}
}
}The first call uses the varargs overload. The DEBUG call uses the supplier overload. The ERROR call uses the overload that takes a Throwable, so the backend records the stack trace.
Message formatting uses MessageFormat
The {0}, {1} placeholders follow java.text.MessageFormat syntax. They are numbered from zero and are not the {} style that SLF4J uses. The format has three consequences that surprise people.
- Numbers are localized.
MessageFormatformats numbers with grouping, so the integer1234can print as1,234. If you need the raw digits, passString.valueOf(n)instead of the number. - Single quotes are special. In
MessageFormat, an apostrophe starts quoted text. A message such as"Can't find {0}"can swallow the placeholder. Write''for a literal apostrophe, or avoid apostrophes in formatted messages. - Formatting is the backend's job. The API defines the syntax, but the backend does the formatting. A backend may skip it when you pass no parameters, so do not rely on
{0}being left alone or replaced in a message with no arguments.
Avoiding wasted work
Building a log message can cost more than the logging itself. Consider LOG.log(Level.DEBUG, "State: " + dump()). Java evaluates dump() and concatenates the string before log runs, even if DEBUG is disabled.
There are two ways to avoid that cost. The first is the Supplier overload. The backend calls the supplier only if the level is enabled. The second is an explicit guard with isLoggable:
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class LevelCheck {
private static final Logger LOG = System.getLogger(LevelCheck.class.getName());
public static void main(String[] args) {
if (LOG.isLoggable(Level.TRACE)) {
LOG.log(Level.TRACE, "Detailed state: {0}", String.join(",", args));
}
LOG.log(Level.WARNING, "Running with {0} arguments", args.length);
}
}The guard skips the String.join call when TRACE is off. The second statement passes only a cheap value, so it needs no guard. It does autobox args.length to an Integer, which is a negligible cost.
A cheap argument does not need a guard or a supplier. Reserve them for work such as serializing an object, walking a collection, or querying something.
You can see laziness directly with a counter:
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class LazyDemo {
private static final Logger LOG = System.getLogger(LazyDemo.class.getName());
private static int calls = 0;
static String expensive() {
calls++;
return "state-" + calls;
}
public static void main(String[] args) {
LOG.log(Level.DEBUG, () -> expensive());
LOG.log(Level.INFO, () -> expensive());
System.out.println("expensive() ran " + calls + " time(s)");
}
}Under the JDK's default configuration, INFO is enabled and DEBUG is not. The program prints expensive() ran 1 time(s), because only the INFO supplier ran. The INFO message itself goes to standard error.
What happens on a log call
The logger decides whether to build the message, and the backend decides whether to write it. The diagram shows the path of one call.
Which backend receives the call, and how it is configured, is the subject of the next chapter. Two facts are enough for now. When the java.logging module is present, the default backend is java.util.logging, and the JDK maps System.Logger levels onto its own. In that setup the root level is INFO, so TRACE and DEBUG messages disappear unless you change the configuration. Without java.logging, a minimal console logger writes to standard error.
Exceptions
Pass the exception as the last argument of the overload that takes a Throwable:
LOG.log(Level.ERROR, "Could not place order " + orderId, e);This overload does not apply any {0} formatting, so build the message yourself. The format, Object... params overload treats every trailing argument as a parameter. If you write LOG.log(Level.ERROR, "Failed: {0}", e), you get only e.toString() and no stack trace. Choose the Throwable overload when you want the trace.
If you need both formatted parameters and a stack trace, build the message with String.format or concatenation, then call the Throwable overload.
Common errors
- Using
WARNinstead ofWARNING.Level.WARNdoes not exist and the code does not compile. - Expecting
DEBUGoutput by default. With the default backend the root level isINFO, so nothing appears. The code is fine and the backend configuration is what needs to change. - Logging
ALLorOFF. These are thresholds, not message levels. - Losing the stack trace. Passing the exception as a format parameter prints only its
toString(). - A shared logger per application. Create one logger per class, named after the class, so backend configuration can target packages.
- Concatenating before the call.
"a" + bruns even when the level is off. Use placeholders for cheap values and a supplier orisLoggablefor expensive ones.
Limits of System.Logger
The API is deliberately small. It has no markers, no per-thread context such as MDC, and no way to attach structured key-value pairs to an event. It also has no {} placeholders. Applications that need those features usually log through SLF4J, which later chapters cover. Because System.Logger can be routed into SLF4J, JDK and library messages can still end up in the same configuration as the rest of your output.
Exercise
A teammate writes LOG.log(Level.ERROR, "Payment failed for {0}", customerId, e); where e is an exception. What does the log contain, and how would you fix the call so the stack trace is recorded?
Show answer
The call matches the format, Object... params overload, so e is treated as a second parameter that no placeholder uses. The stack trace is not recorded. To fix it, build the message first and use the Throwable overload: LOG.log(Level.ERROR, "Payment failed for " + customerId, e);.
Exercise
You need to log a large collection's contents at DEBUG using System.Logger. Show two ways to avoid building the string when DEBUG is off.
Show answer
Use the supplier overload: LOG.log(Level.DEBUG, () -> "Items: " + items);. Or guard the call: if (LOG.isLoggable(Level.DEBUG)) { LOG.log(Level.DEBUG, "Items: {0}", items); }. In both cases the expensive string conversion runs only when DEBUG is enabled.