Sub topic 2
Log levels: DEBUG to CRITICAL
This chapter assumes you can write Python functions and modules and use try/except. It also assumes you have run a script from a terminal. The previous chapter explained why logging beats print. This chapter covers the feature that makes it work: severity levels. You will learn what the five standard levels mean and how Python compares them with thresholds. You will also learn how to choose a level for an event and how to avoid common mistakes.
What a level is
A level is a severity label attached to every log record. Internally it is an integer. Python compares that integer with a threshold, and if the record is below the threshold, it is discarded.
| Level | Number | Typical meaning |
|---|---|---|
| `DEBUG` | 10 | Detail useful when diagnosing a problem |
| `INFO` | 20 | Confirmation that things work as expected |
| `WARNING` | 30 | Something unexpected happened, or a problem is likely soon, but the program continues |
| `ERROR` | 40 | An operation failed |
| `CRITICAL` | 50 | The program may be unable to continue |
There is also NOTSET (0). You do not log at this level. It is a setting that means "no level of my own here". The next sections show where that matters.
You can print the numbers yourself:
import logging
for name in ("NOTSET", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):
print(f"{name:<9} {getattr(logging, name)}")Because levels are plain integers, "at least WARNING" means "greater than or equal to 30". This is why the ordering is meaningful and why you can define your own levels between the standard ones.
Emitting records at each level
Every logger has one method per level, named in lowercase:
import logging
logging.basicConfig(level=logging.DEBUG, format="%(levelname)-8s %(message)s")
logger = logging.getLogger("demo")
logger.debug("Cache key computed: %s", "user:42")
logger.info("Server started on port %d", 8080)
logger.warning("Disk usage at %d%%", 91)
logger.error("Could not save order %s", "A-1001")
logger.critical("Database unreachable, shutting down")Each line shows its level name. Note that the messages use %s and %d placeholders with separate arguments instead of an f-string. Python only builds the final string if the record is actually going to be emitted. A suppressed debug call therefore costs almost nothing, and the unformatted template also makes records easier to group in log tools.
Two other spellings exist. logger.warn() is a deprecated alias of warning(), so avoid it. logger.fatal() is an alias of critical(). When the level is only known at run time, use logger.log(level, msg, *args):
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
logger = logging.getLogger("demo")
def report(ok: bool) -> None:
level = logging.INFO if ok else logging.ERROR
logger.log(level, "Job finished, success=%s", ok)
report(True)
report(False)How a threshold filters records
A record has to pass two level checks before it appears anywhere.
- The logger compares the record's level with its effective level. If the record is lower, it is dropped and no record object is even created.
- Each handler that receives the record compares it with the handler's own level. A handler may skip a record that another handler accepts.
The second check is why one logger can feed a quiet console and a detailed file. The effective level of the logger must be low enough for the most verbose handler:
import logging
logger = logging.getLogger("myapp")
logger.setLevel(logging.DEBUG) # let everything reach the handlers
console = logging.StreamHandler()
console.setLevel(logging.WARNING) # console: warnings and worse
logfile = logging.FileHandler("levels-demo.log", encoding="utf-8")
logfile.setLevel(logging.DEBUG) # file: everything
logger.addHandler(console)
logger.addHandler(logfile)
logger.debug("File only")
logger.error("Console and file")A frequent mistake is to set a handler to DEBUG but leave the logger at its default. The logger drops the record at check 1, so the handler never sees it.
The effective level and `NOTSET`
A logger created with getLogger("myapp.db") starts at NOTSET. When a logger is NOTSET, Python walks up through its parents (myapp, then the root logger) and uses the first level that is not NOTSET. That value is what getEffectiveLevel() returns. The hierarchy gets its own chapter, but you need this much now:
import logging
logging.getLogger().setLevel(logging.WARNING) # root logger
child = logging.getLogger("myapp.db")
print(child.level) # 0 (NOTSET)
print(child.getEffectiveLevel()) # 30 (inherited WARNING)
print(child.isEnabledFor(logging.INFO)) # FalseThe root logger's default level is WARNING. That default explains a very common surprise: in a script with no configuration, logger.info("hello") prints nothing, while logger.warning("hello") prints. When no handler is configured at all, Python falls back to a "last resort" handler that writes WARNING and above to standard error, with only the message text and no timestamp.
Choosing the right level
The names are guidance, not law, but consistent use makes logs searchable. These questions help decide:
- DEBUG: Would only a developer chasing a bug want this? Variable values, SQL text, branch decisions, and loop iterations belong here. Expect to disable it in production.
- INFO: Does it record a normal milestone that an operator would want in a timeline? Service started, job completed, configuration loaded.
- WARNING: Did something odd happen that the program handled, or is a limit approaching? A retry succeeded on the second try, a deprecated option was used, disk usage is high.
- ERROR: Did a specific operation fail while the program as a whole keeps running? A request failed, a file could not be parsed.
- CRITICAL: Is the whole program or an essential component in danger? Out of memory, a required database is gone, a startup check failed.
Two practical tests help. First, if a person should be woken up or alerted, it is ERROR or higher. Second, if the message would be noise at 1,000 lines per second, it is not INFO.
A related trap is logging the same failure at several layers. If a low-level function logs an ERROR and then re-raises, and the caller logs the same exception again, you get duplicate entries. Log where you handle the exception, not where you pass it along.
Expensive arguments and `isEnabledFor`
Lazy %s formatting avoids building the message string, but it does not avoid evaluating the arguments. If an argument is expensive to compute, guard the call:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("demo")
def expensive_dump(data):
return ",".join(str(x) for x in sorted(data))
data = {3, 1, 2}
if logger.isEnabledFor(logging.DEBUG):
logger.debug("State: %s", expensive_dump(data))With the level at INFO, expensive_dump never runs. For cheap values, skip the guard and keep the code simple.
Switching levels without editing code
A common pattern is to take the level from the environment, so you can raise verbosity for one run:
import logging
import os
level_name = os.environ.get("LOG_LEVEL", "INFO").upper()
logging.basicConfig(level=level_name, format="%(levelname)s %(name)s: %(message)s")
logging.getLogger("app").debug("Visible only when LOG_LEVEL=DEBUG")
logging.getLogger("app").info("Visible by default")Running LOG_LEVEL=DEBUG python script.py shows both lines. An invalid value fails immediately at startup with ValueError, which is usually what you want.
Silencing everything and custom levels
logging.disable(level) overrides every logger: records at that level or below are discarded, whatever the individual settings are. logging.disable(logging.CRITICAL) silences all standard levels, and logging.disable(logging.NOTSET) turns normal behavior back on. This is mainly useful in test suites.
You can add a named level with logging.addLevelName(25, "NOTICE") and emit it with logger.log(25, ...). Most projects do not need this. Custom levels make logs harder to interpret for people who know only the standard five, and tools that expect the standard names may not handle them.
Summary of the rules
- Levels are integers, and a threshold keeps everything at or above it.
- The logger's effective level is checked first, then each handler's level.
NOTSETmeans "inherit from the parent". The root logger defaults toWARNING.- Choose the level by who needs the information and how urgently.
- Pass arguments separately, and guard only genuinely expensive computations.
Exercise
A logger named "shop" has no level set, and the root logger's level is WARNING. The "shop" logger has one handler with its level set to DEBUG. You call logger.info("Order placed"). Is the message printed, and why? What is the smallest change that makes it appear?
Show answer
It is not printed. The "shop" logger is NOTSET, so its effective level is WARNING, inherited from the root. The INFO record fails the logger's check and is dropped before it reaches the handler, so the handler's DEBUG level never matters. The smallest fix is logger.setLevel(logging.INFO), or logging.DEBUG if you also want debug records to reach the handler.
Exercise
Why is logger.debug("User: %s", user) preferred over logger.debug(f"User: {user}")? In which case would you still wrap the call in logger.isEnabledFor(logging.DEBUG)?
Show answer
With %s and a separate argument, the message string is built only if the record passes the level check, so a suppressed call is cheap. The f-string is always built first. You would still add the isEnabledFor guard when computing the argument itself is expensive, for example serializing a large data structure, because lazy formatting does not delay evaluating the arguments.