Sub topic 3
Logging with `System.Logger`
Prerequisites
This chapter assumes basic Java classes and methods, try/catch, and the ability to compile and run a Java program. System.Logger is the logging interface included in the JDK since Java 9. It lets application code write log events without depending directly on one logging implementation.
Why use `System.Logger`?
A log event is a record of something that happened while a program ran. Logs help you diagnose failures, understand important business events, and monitor a running application.
A logging API is a set of classes and methods that application code calls. A logging backend is the component that decides where events go, such as the console, a file, or a monitoring service.
Using an API instead of calling a backend directly separates your code from the output configuration:
- Your class says what happened.
- The backend decides whether to display the event.
- Configuration can change the output without changing application code.
- A disabled log level can avoid unnecessary work.
System.Logger is obtained from System, so it needs no dependency:
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 == null || 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);
}
}
public static void main(String[] args) {
new OrderService().place("A-1042");
new OrderService().place("");
}
}The Logger field is usually static final, because every instance of the class can share the same named logger. The name is commonly the class name.
Choosing a level
A level describes the importance or detail of an event. The backend normally filters events below its configured threshold.
| Level | Typical use |
|---|---|
| `TRACE` | Very detailed diagnostic information |
| `DEBUG` | Developer-oriented state and flow information |
| `INFO` | Normal, meaningful application events |
| `WARNING` | An unusual condition that did not stop the operation |
| `ERROR` | A failure that needs attention |
| `ALL` | Enables every level |
System.Logger.Level also includes OFF, which disables logging. Use WARNING, not WARN; the names differ from some third-party APIs.
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)) {
String details = String.join(",", args);
LOG.log(Level.TRACE, "Detailed state: {0}", details);
}
LOG.log(Level.WARNING, "Running with {0} arguments", args.length);
}
}isLoggable is useful when preparing a message requires noticeable work. Do not use INFO for every message. A high-volume diagnostic event belongs at DEBUG or TRACE.
Formatting messages and delaying work
The {0} syntax uses java.text.MessageFormat style numbering. Additional arguments replace {0}, {1}, and later placeholders.
The Supplier<String> overload accepts a function that creates the message. The function runs only when the selected level is enabled. This avoids building an expensive message unnecessarily.
The overload that accepts a Throwable records the exception and its stack trace. A stack trace is the sequence of method calls that led to an exception.
How a log event is routed
The System.Logger API does not require one fixed output format. The JDK selects a backend for each logger. The default behavior commonly uses the platform logging mechanism, while applications can install another LoggerFinder through the Java platform logging mechanism.
This design means that application code should focus on useful events and correct levels. Backend selection and formatting belong in deployment configuration.
Exercise
Which overload should you use when an error must include its exception stack trace?
Show answer
Use log(Level, String, Throwable), for example LOG.log(Level.ERROR, "Could not place order", exception).