December 5, 2026

Python Logging Basics: Levels, Handlers, and the Warning That Breaks Your Config

An open logbook beside a brass compass on a chart table

A script calls logging.warning() once near the top, then sets up logging properly a few lines later with logging.basicConfig(level=logging.DEBUG). Every debug message after that disappears. No error, no warning about the configuration, just silence where the output should be. Python’s logging module is flexible enough to run large applications and quirky enough to confuse anyone who learned it from one snippet. Every example below was run on Python 3.13, and the output shown is what the interpreter printed.

Video: Corey Schafer on YouTube

Why logging instead of print

What the docs recommend

The Python logging HOWTO has a table for this. For ordinary console output of a command-line program, print() is the right tool. For reporting events during normal operation, such as status monitoring or fault investigation, use a logger’s info(), or debug() for very detailed diagnostic output. Errors that are handled without being raised get error(), exception() or critical().

What logging adds

A log message carries a level, a timestamp, the name of the module that produced it, and can go to the console, a file, the system log or anywhere else, all configured in one place. A print() statement left in code goes to standard output forever. A logger.debug() call can be silenced in production and switched on again when something breaks, without editing the code.

The format string does a lot of work

Most of logging’s usefulness comes from the format. A pattern such as %(asctime)s %(levelname)s %(name)s:%(lineno)d %(message)s stamps every line with the time, the severity, the logger’s name and the line number that produced it. Months later, when a log file is the only witness to what went wrong, those fields are the difference between a clue and a guess. print() offers none of them unless they are typed in by hand at every call.

Green and yellow round candies in clear glass

Levels and the default

Five levels

From lowest to highest: DEBUG, INFO, WARNING, ERROR, CRITICAL. A logger set to a level shows messages at that level and above.

The default hides half of them

import logging
logging.debug("debug msg")
logging.info("info msg")
logging.warning("warning msg")
logging.error("error msg")

Output:

WARNING:root:warning msg
ERROR:root:error msg

The HOWTO explains: the default level is WARNING, so only events of that severity and higher are tracked unless logging is configured otherwise. Debug and info calls ran and produced nothing. People adding logging.info() to a script and seeing no output usually hit exactly this.

basicConfig and the trap

basicConfig sets up the root logger

logging.basicConfig() attaches a handler to the root logger and sets its level and format in one call:

logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s %(levelname)s %(name)s: %(message)s")

It only works once

The logging library reference states that basicConfig() does nothing if the root logger already has handlers configured, unless force=True is passed. Calling it twice proved it:

logging.basicConfig(level=logging.INFO, format="%(message)s")
logging.basicConfig(level=logging.DEBUG, format="SECOND %(message)s")
logging.debug("hidden?")
logging.info("info shows with first format")

The debug line never appeared, and the info line printed with the first format. The second call was ignored silently. Adding force=True to a later call, available since Python 3.8, removed the old handler and applied the new settings: the next debug message printed as FORCED now visible.

The trap from the introduction

logging.warning("before config")
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logging.debug("after config")

Output:

WARNING:root:before config

The HOWTO explains why: module-level functions like logging.warning() call basicConfig() for you if it hasn’t been called yet. The early warning configured the root logger with defaults, and the real basicConfig() a line later did nothing. The HOWTO also says the call to basicConfig() should come before any calls like debug() or info(). In practice that means configuring logging at the very start of the program, before importing modules that might log at import time.

A coat rack with hats and scarves hanging on it

Named loggers and propagation

One logger per module

The HOWTO recommends a module-level logger named after the module:

logger = logging.getLogger(__name__)

Logger names follow the package hierarchy, so a message from app.db shows exactly where it came from, and its level can be set separately from app.web.

Messages climb the tree

The HOWTO describes propagation: child loggers pass messages up to the handlers of their ancestor loggers, so it is enough to configure handlers on a top-level logger. A named logger with its own handler, under a root logger that also has one, produces two copies of every message:

log = logging.getLogger("app.db")
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
log.addHandler(logging.StreamHandler())
log.info("connected")

Output:

connected
INFO app.db: connected

The first line came from the handler on app.db; the second from the root handler, reached by propagation. The fix is to attach handlers in one place, normally the top of the hierarchy, or to set log.propagate = False on a logger that has its own.

Logging from inside a library

Code written to be imported by other programs follows a different rule. With no configuration at all, a named logger’s warning still printed, as a bare message with no level or name:

library warning, no config

The HOWTO explains this as a “handler of last resort,” which writes events of WARNING and above to standard error without formatting when no handler is found. A library that wants to stay quiet by default can attach a NullHandler to its top-level logger; in the test, adding one made the same warning vanish. The HOWTO is emphatic about the other half: it strongly advises against adding any handler other than NullHandler to a library’s loggers, because choosing where logs go belongs to the application developer. A library that installs its own console handler takes that choice away and tends to produce duplicate messages in every program that imports it.

Handlers, levels and rotating files

Two places to filter

A logger has a level, and each handler has its own. A record has to pass both. The test set the app logger to DEBUG, a file handler to INFO and a console handler to WARNING, then logged twenty info lines, one debug line and one warning:

  • The console showed only disk almost full, the warning.
  • The file received the info lines and the warning.
  • The debug line went nowhere: it passed the logger but neither handler.

That pattern, verbose to a file and quiet on screen, is the most common reason to use handlers directly instead of basicConfig().

RotatingFileHandler

The logging.handlers documentation says rollover happens when the file nears maxBytes, renaming app.log to app.log.1 and shifting older files up, and that if either maxBytes or backupCount is zero, rollover never occurs. With maxBytes=200 and backupCount=2, the test ended with:

['app.log', 'app.log.1', 'app.log.2']  sizes: [113, 192, 192]

After 20 lines nothing was lost yet: app.log.2 held lines 0 to 7, app.log.1 lines 8 to 15, and app.log the rest. Running the same script with 40 lines told a different story. The oldest surviving line was number 24; lines 0 through 23 had been deleted as the oldest backup rotated out each time. That is the design: a rotating log caps disk use by discarding the oldest history. backupCount decides how much history survives, and setting it to zero doesn’t keep everything; it turns rotation off and lets the file grow without limit.

Rotation by time

The same page describes TimedRotatingFileHandler, whose when option rotates by seconds, minutes, hours, days, a weekday or midnight. Daily logs kept for a fixed number of days usually use when="midnight" with a backupCount.

A wooden tray contains toys and accessories

Exceptions and formatting

logging.exception keeps the traceback

try:
    1/0
except ZeroDivisionError:
    logging.exception("calculation failed")

Output:

ERROR root: calculation failed
Traceback (most recent call last):
  File "/tmp/p21/d.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero

The library reference says exception() logs at ERROR level with exception information added, and should only be called from an exception handler. It replaces the common logging.error(str(e)), which keeps the message and throws away the line number where things went wrong.

Pass arguments, don’t pre-format

The reference explains that the message and its arguments are merged with the % operator when the record is formatted, and a message that is filtered out by level is never formatted. The test logged a debug message, below the configured INFO level, with an object whose string conversion took half a second:

Call Time spent
logging.debug("value %s", obj) 0.00 s
logging.debug(f"value {obj}") 0.50 s

The f-string built the string before debug() was even called, then the message was thrown away. With arguments passed separately, the expensive conversion never ran. In a loop, or with debug logging switched off in production, the difference adds up.

A minimal setup that avoids every trap above

import logging
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger(__name__)

Configure first, once, at the top of the entry point. Use named loggers everywhere else. Pass arguments instead of building strings, and reach for logger.exception() inside every except block that doesn’t re-raise. The module rewards being set up correctly once far more than being patched later, because nearly all of its failures are silent.

Sources

  • Logging HOWTO, Python documentation: https://docs.python.org/3/howto/logging.html
  • logging: Logging facility for Python, Python documentation: https://docs.python.org/3/library/logging.html
  • logging.handlers: Logging handlers, Python documentation: https://docs.python.org/3/library/logging.handlers.html

820 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *