Sub topic 3
Understanding log levels
This chapter assumes you can write a basic Spring Boot application and have seen application.properties. It also assumes you know that Spring Boot uses SLF4J with Logback by default. You will learn what each level means, how a level decides whether a message is written, and the defaults and edge cases that surprise people.
What a log level does
Every log statement has a level. Every logger also has a level, called its threshold. A message is written only if its level is at least as severe as the logger's threshold. Otherwise the framework discards it, and the call costs very little.
SLF4J defines five levels. Spring Boot also accepts FATAL and OFF in configuration.
| Level | Severity order | Typical use |
|---|---|---|
| TRACE | 1 (lowest) | Very fine detail, such as method entry and exit or every loop pass |
| DEBUG | 2 | Diagnostic detail for developers, such as computed values and branch decisions |
| INFO | 3 | Normal milestones, such as startup complete, order placed, job finished |
| WARN | 4 | Something unexpected happened, but the application recovered or can continue |
| ERROR | 5 (highest) | An operation failed and someone may need to act |
| FATAL | Not in SLF4J | Accepted in Spring Boot configuration, but Logback treats it as ERROR |
| OFF | Above all | Turns logging off for that logger |
If a logger's threshold is INFO, it writes INFO, WARN and ERROR. It drops DEBUG and TRACE. Lowering the threshold gives you more output, and raising it gives you less.
Choosing the right level
The level is a promise to whoever reads the logs. A reader who filters for WARN and above expects to see only things worth attention. These rules of thumb work well in practice.
- ERROR: An operation failed and was not completed. A payment was rejected because the gateway was down. A database write failed. Do not use ERROR for expected conditions such as a user typing a wrong password.
- WARN: Something is off, but the request still worked. A retry succeeded on the second attempt. A deprecated API was called. A cache was unavailable and the code fell back to the database.
- INFO: Events an operator wants in a normal production log. They should be few and meaningful. One line per business event is usually fine. One line per loop pass is not.
- DEBUG: Details you need when diagnosing a problem. Parameters, intermediate results and which branch ran. You normally turn this on for one package at a time.
- TRACE: Even finer detail than DEBUG. Many teams rarely use it in application code. Libraries such as Hibernate and Spring Security use it to show internals.
A useful test is to ask who needs the message and when. If the answer is "an on-call engineer, immediately", use ERROR. If it is "me, while debugging this feature", use DEBUG.
Seeing levels in action
The class below logs one message at each level. It runs once at startup because it implements CommandLineRunner.
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class LevelDemo implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(LevelDemo.class);
@Override
public void run(String... args) {
log.trace("trace message");
log.debug("debug message");
log.info("info message");
log.warn("warn message");
log.error("error message");
}
}Run the application with no logging configuration. Only three of the five messages appear (the timestamp, process ID and thread columns are omitted here):
INFO --- c.example.demo.LevelDemo : info message
WARN --- c.example.demo.LevelDemo : warn message
ERROR --- c.example.demo.LevelDemo : error messageSpring Boot sets the root logger's threshold to INFO by default. That is why trace and debug produced nothing.
To lower the threshold for this package only, pass a property on the command line. Properties files are covered in a later chapter. Here you only need to see the effect.
java -jar target/demo.jar --logging.level.com.example.demo=traceAll five messages now appear.
Effective level and inheritance
Loggers form a tree based on their names. The logger com.example.orders.OrderService is a child of com.example.orders, which is a child of com.example, then com, and finally the root logger.
A logger that has no level of its own inherits the level of its nearest ancestor that has one. The result is its effective level. Consider this setup:
- Root is
INFO. com.example.ordersisDEBUG.
Then com.example.orders.OrderService and com.example.orders.payment.PaymentClient both have an effective level of DEBUG. A class in com.example.billing has no level of its own and none on its path except the root, so it stays at INFO.
A more specific setting always wins over a broader one. This is how you can keep the whole application quiet and still get detail from one package.
Defaults and the debug and trace switches
Spring Boot's defaults are worth knowing, because they explain why a fresh application is quiet.
- The root level is
INFO. - Some noisy libraries are tuned further. Spring Boot lowers the output of several Tomcat, Jetty and Hibernate loggers by default so startup stays readable.
- Output goes to the console. A log file is written only if you configure one.
Two startup flags exist for quick diagnosis: --debug and --trace. They are often misunderstood.
java -jar target/demo.jar --debug--debug (or debug=true in properties) switches a selected set of core loggers to DEBUG. These cover the embedded web container, Hibernate, and Spring Boot itself. It also prints the auto-configuration report. It does not change the level of your own packages. Running LevelDemo with --debug still shows only INFO, WARN and ERROR for com.example.demo. --trace does the same for TRACE.
FATAL, OFF and case handling
SLF4J has no FATAL level, and Logback does not either. Spring Boot lets you write fatal in configuration for compatibility with other backends, but Logback maps it to ERROR. Log4j2 has a real FATAL level, so the value behaves differently if you switch backends later.
OFF disables a logger completely. It is useful for silencing one chatty library:
logging.level.org.hibernate.engine.jdbc.spi.SqlExceptionHelper=offUse this carefully. A logger set to OFF also hides real errors from that library, which can make a failure invisible.
Level names in properties are not case sensitive. debug, DEBUG and Debug all work. An unrecognized name is treated as DEBUG by Logback's own parser, not as an error, so a typo can produce more output than you expected. Check the spelling when you see an unusual amount of logging.
Cost of disabled levels
A disabled call is cheap, but its arguments are still evaluated before the call. In this statement the expensive method runs even when DEBUG is off:
log.debug("State: {}", buildLargeReport());The {} placeholder avoids string concatenation work, but it cannot prevent buildLargeReport() from running. If building the argument is costly, guard it with a level check:
if (log.isDebugEnabled()) {
log.debug("State: {}", buildLargeReport());
}SLF4J 2, which Spring Boot 3 uses, also offers a fluent API with a supplier, so the work is skipped when the level is off:
log.atDebug().setMessage("State: {}").addArgument(() -> buildLargeReport()).log();For plain values such as IDs and counts, no guard is needed. The next chapter covers parameterized messages in detail.
Common mistakes with levels
- Logging everything at INFO. Production logs become too large to read, and real problems drown in routine lines.
- Logging expected failures as ERROR. Validation failures and "not found" results for user lookups are normal. If every one raises an ERROR, alerts stop being trustworthy.
- Logging the same failure at several layers. If a service logs an exception at ERROR and then rethrows it, and the controller advice logs it again, one failure appears as several errors. Log at the point where you handle the exception.
- Leaving DEBUG on in production. It costs disk, CPU and money for log storage, and it may expose personal data. Raise it temporarily for one package instead.
- Assuming
--debugcovers your code. See the warning above.
Exercise
A Spring Boot application has logging.level.root=warn and logging.level.com.example.orders=debug. A class com.example.orders.web.OrderController calls log.debug(...), log.info(...) and log.warn(...). A class com.example.billing.InvoiceService makes the same three calls. Which of the six messages are written, and why?
Show answer
All three messages from OrderController are written. Its effective level is DEBUG, inherited from com.example.orders, and DEBUG, INFO and WARN are all at or above that threshold. For InvoiceService, no ancestor except the root has a level, so its effective level is WARN. Only its log.warn(...) message is written, and its debug and info messages are discarded.
Exercise
You start the application with --debug, but your own log.debug(...) calls in com.example.shop still produce no output. Why, and what is the smallest change that fixes it?
Show answer
--debug only lowers the level of a selected set of core loggers (the embedded container, Hibernate and Spring Boot), not application packages. The com.example.shop loggers still inherit INFO from the root. Setting logging.level.com.example.shop=debug fixes it for that package only.