Sub topic 2
Log levels: DEBUG to CRITICAL
This chapter assumes you can write Python functions and modules and run scripts from a terminal. It also assumes you have seen import logging before. Here you learn what each level means and how a level decides whether a message is kept or dropped.
What a level is
Every log record has a severity called a level. Each level is an integer, and the logging module defines five standard ones.
| Level | Value | Typical use |
|---|---|---|
| DEBUG | 10 | Details for diagnosing a problem, such as variable values |
| INFO | 20 | Normal events, such as "server started" |
| WARNING | 30 | Something unexpected, but the program continues |
| ERROR | 40 | An operation failed |
| CRITICAL | 50 | The program may not be able to continue |
There is also NOTSET (0). On a logger, it means "no level of its own, so ask the parent". The hierarchy chapter covers this.
Choosing a level
Ask who needs to see the event and what they should do about it.
- Use DEBUG for information only a developer needs while investigating.
- Use INFO to confirm that things work as expected.
- Use WARNING for a recoverable surprise, such as a deprecated setting or a retry.
- Use ERROR when a specific task failed but the program keeps running.
- Use CRITICAL when the whole program is in danger, such as a lost database connection it cannot recover.
The threshold rule
A logger has a threshold. A record is processed only if its level is greater than or equal to the threshold. Anything lower is discarded before any handler sees it.
The root logger's default threshold is WARNING. A script that calls logger.info(...) without configuration prints nothing. This surprises many people.
Setting the threshold
basicConfig sets the root logger's threshold. The example below uses INFO, so the DEBUG call is dropped.
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logger = logging.getLogger(__name__)
logger.debug("Loaded %d rows", 250)
logger.info("Import started")
logger.warning("Config key 'timeout' missing, using default")
logger.error("Could not write report")
logger.critical("Disk full, shutting down")
print(logger.isEnabledFor(logging.DEBUG))
print(logger.getEffectiveLevel() == logging.INFO)It prints four log lines to stderr, starting with INFO: Import started. The DEBUG line is missing. The two print calls then show False and True.
You can pass a level as a constant (logging.INFO) or as a string ("INFO"). Strings must be uppercase.
Cost of disabled messages
A dropped record is cheap, but arguments are still evaluated before the call. Pass values as arguments and let logging format them, as in logger.debug("Loaded %d rows", n). The string is built only if the record passes the threshold. An f-string builds the text every time. For expensive work, guard it:
if logger.isEnabledFor(logging.DEBUG):
logger.debug("State: %s", build_expensive_report())Levels on handlers
A handler has its own threshold too. The logger filters first, then each handler filters again. A common setup gives the logger DEBUG, the console INFO, and a file DEBUG. The next chapters build this.
Exercise
A script calls logging.basicConfig(level=logging.ERROR) and then logs one message each at DEBUG, WARNING, ERROR, and CRITICAL. Which messages are printed, and why?
Show answer
ERROR and CRITICAL are printed. The threshold is 40, so a record is kept only if its level is 40 or higher. DEBUG (10) and WARNING (30) are below the threshold and are discarded.
Exercise
Why is logger.debug("Total: %s", total) preferred over logger.debug(f"Total: {total}")?
Show answer
With the %s form, logging builds the message string only if the record passes the level check. The f-string builds the text before the call, even when DEBUG is disabled and the message is thrown away.