Sub topic 2
Choosing log levels
This chapter assumes you can read basic Java and know what a log statement is. It also assumes you have seen the idea of a logging facade from the previous chapter. You don't need to know the System.Logger or SLF4J APIs yet. Later chapters cover them. Here you learn what each level means and how a threshold decides which messages appear.
What a level does
Every log statement carries a level, which says how important or how detailed the message is. The logging backend has a configured threshold. A message is written only if its level is at or above that threshold. Everything below it is discarded.
Levels are ordered from most detailed to most severe. With a threshold of INFO, messages at INFO, WARN and ERROR appear. Messages at DEBUG and TRACE do not.
The threshold is a deployment decision, not a code decision. You write DEBUG statements once. Operators then switch them on or off through configuration without recompiling. This is why choosing the right level at the call site matters. The level is the only control a future reader of the logs will have.
The levels and what they mean
The two APIs in this tutorial name their levels slightly differently. The meanings are the same.
| Meaning | System.Logger | SLF4J | java.util.logging |
|---|---|---|---|
| Finest-grained detail, step by step | TRACE | TRACE | FINER |
| Diagnostic detail for developers | DEBUG | DEBUG | FINE |
| Normal, notable events | INFO | INFO | INFO |
| Unexpected but handled, may need attention | WARNING | WARN | WARNING |
| An operation failed | ERROR | ERROR | SEVERE |
System.Logger also defines two special levels, ALL and OFF. They are used for configuration, not for logging. A threshold of ALL enables every message, and a threshold of OFF disables all of them. You don't pass ALL or OFF to a log call.
SLF4J has no FATAL level. Some older libraries, such as Log4j 1.x and Apache Commons Logging, do have one. If you bridge them into SLF4J, their fatal messages arrive as ERROR.
The JDK's own mapping from System.Logger to java.util.logging is worth knowing. When the default backend is java.util.logging, TRACE becomes FINER and DEBUG becomes FINE. The java.util.logging default threshold is INFO. So with no configuration, a System.Logger DEBUG call produces nothing.
TRACE
TRACE is for very fine-grained flow: method entry and exit, loop iterations, values of intermediate variables. It is normally off everywhere, including in development, and is turned on for one class or package while you chase a specific bug. Expect TRACE statements to be numerous. Never leave one in a hot loop without a plan for its cost.
DEBUG
DEBUG records information a developer needs to understand what the program did: which branch was taken, which configuration value was resolved, what a downstream call returned in summary. It is on in development and usually off in production. It is also the level you switch on temporarily in production for one package when diagnosing an incident.
INFO
INFO records events that describe the normal life of the application: startup and shutdown, a configuration summary, a scheduled job finishing, a business event such as an order being placed. A good test is whether an operator reading only INFO lines could tell what the application has been doing, without being flooded. INFO is the usual production threshold.
WARN
Use WARN (WARNING in System.Logger) when something unexpected happened but the application handled it and continues correctly. Examples: a retry succeeded on the second attempt, a deprecated setting was used, a cache was unavailable and the code fell back to the database, a request had invalid input that was rejected. A WARN says "look at this if it keeps happening." A single WARN should not require anyone to act at 3 a.m.
ERROR
Use ERROR when an operation failed and the application could not do what it was asked to do. Examples: a payment could not be charged, a message could not be written to the queue after all retries, a required file was missing at startup. Alerts are commonly attached to ERROR. That is the reason to be strict about it. If you log ERROR for conditions nobody needs to act on, the alert stops meaning anything.
Deciding between adjacent levels
Most real disagreements are between two neighbouring levels. These questions settle them.
- WARN or ERROR? Did the operation the caller asked for succeed? If it did, even through a fallback, use WARN. If it did not, use ERROR.
- INFO or DEBUG? Would an operator running the system want this line every day? If yes, INFO. If only a developer investigating a problem wants it, DEBUG.
- DEBUG or TRACE? Does the message describe a decision or a result, or does it describe each tiny step? Decisions and results are DEBUG. Per-step detail is TRACE.
A frequent case is bad user input. A user submitting an empty form field is not an application failure. The application worked and rejected the input, so the level is INFO or WARN at most, and often DEBUG. Logging it at ERROR makes a user's typo look like an outage.
Another common case is a retry. Log each failed attempt at WARN, because the code is handling it. Log ERROR only when the final attempt fails and the operation is abandoned.
Seeing thresholds in action
The following program uses System.Logger, which the next chapter explains in detail. For now, read it for the levels. It runs on Java 9 or later with no extra dependencies, using the JDK's default backend.
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class LevelDemo {
private static final Logger LOG = System.getLogger(LevelDemo.class.getName());
public static void main(String[] args) {
LOG.log(Level.TRACE, "Entering main");
LOG.log(Level.DEBUG, "Parsed {0} arguments", args.length);
LOG.log(Level.INFO, "Application started");
LOG.log(Level.WARNING, "No configuration file found, using defaults");
LOG.log(Level.ERROR, "Could not connect to the database");
}
}With the default java.util.logging configuration, the console receives only the INFO, WARNING and ERROR lines. The TRACE and DEBUG calls are filtered because the default threshold is INFO. The JDK maps WARNING to its own WARNING and ERROR to SEVERE, so the output labels may read WARNING and SEVERE.
Now the same idea with SLF4J. It needs the dependencies shown later in the tutorial, so only the call sites matter here.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Levels {
private static final Logger log = LoggerFactory.getLogger(Levels.class);
public void run() {
log.trace("Entering run");
log.debug("Loaded {} rules", 12);
log.info("Rules engine ready");
log.warn("Rule set is older than 30 days");
log.error("Rules engine failed to start");
}
}SLF4J gives each level its own method, so the level name is part of the call. System.Logger uses a single log method with a level argument.
Hierarchical thresholds
Thresholds are not global. Backends attach them to named loggers, and logger names are usually class names, which form a hierarchy by package. A logger named com.example.payments.PaymentService inherits its threshold from com.example.payments, then com.example, then com, then the root logger, taking the first one that is set explicitly.
This allows a setup such as:
- Root threshold INFO for the whole application.
com.example.paymentsat DEBUG while you investigate a payment problem.- A noisy third-party library at WARN to quiet it.
Logback configuration for this is covered in a later chapter. The point here is that level choice and threshold choice are separate. Developers choose the level of each statement by meaning. Operators choose thresholds per package by need.
Common mistakes
Everything at INFO. Teams that fear missing a message put it all at INFO. The logs grow until nobody reads them, and the useful lines drown. Move step-by-step detail to DEBUG.
Logging a handled condition at ERROR. If your code catches an exception and recovers, that is WARN. Reserve ERROR for failure of the operation.
Logging and rethrowing. Catching an exception, logging it at ERROR and then throwing it again produces the same failure many times in the logs, once per layer. Log it once, at the layer that finally handles it. A later chapter treats exception logging in detail.
Using levels as a way to send a message to a person. A log level describes the event, not the audience. Don't use ERROR to "make sure someone sees this." If something needs attention, decide what the event really is.
Expecting DEBUG to appear under the default backend. The JDK default threshold is INFO. Missing DEBUG output is almost always a threshold, not a bug in the call.
Checking whether a level is enabled
Because DEBUG and TRACE are usually off, the work to build their messages is wasted when they are disabled. Both APIs let you ask whether a level is enabled first. System.Logger offers isLoggable(Level), and SLF4J offers methods such as isDebugEnabled(). The following chapters on parameterized messages show when this matters and when placeholders make the check unnecessary. For now, remember that choosing DEBUG for a statement also means choosing that its cost is only paid when someone asks for DEBUG output.
Summary of rules of thumb
| Level | Typical production state | Typical audience | Typical content |
|---|---|---|---|
| TRACE | Off | Developer, one class at a time | Per-step flow |
| DEBUG | Off, enabled temporarily | Developer | Decisions and results |
| INFO | On | Operator | Lifecycle and business events |
| WARN | On | Operator, reviewed regularly | Handled surprises |
| ERROR | On, alerted | On-call engineer | Failed operations |
Exercise
A service calls a remote pricing API. The first call times out, the code retries after one second, and the second call succeeds. The customer gets the correct price. At which level would you log the timeout, and why? Which level would you use if all three attempts time out and the customer sees an error?
Show answer
Log the first timeout at WARN. The condition is unexpected, but the code handled it and the requested operation succeeded. If all attempts fail, log once at ERROR, because the operation failed and the application could not do what it was asked to do. Each intermediate failed attempt can stay at WARN, and the final failure is the one ERROR.
Exercise
You run LevelDemo from this chapter with the default JDK backend and see only three lines. Which calls are missing, and what does that tell you about the default threshold?
Show answer
The TRACE and DEBUG calls are missing. The default java.util.logging threshold is INFO, so only INFO, WARNING and ERROR messages are written. System.Logger maps TRACE to FINER and DEBUG to FINE, and both are below INFO.