Skip to content

Lesson 35 of 52Python power tools

The logging Module

How Python's logging really works: loggers, handlers, levels and propagation, configuring it once, logging errors with context, and the bugs everyone hits.

16 min read0/5 questions

At 2 a.m. a job fails in production and the only clue is the output it left behind. If that output is a few print calls, you have no timestamps, no idea which module said what, and no way to turn up the detail without a redeploy. Python's logging module solves this, and every serious library you use (requests, SQLAlchemy, Uvicorn, boto3) already speaks it. Its design confuses people because it has more moving parts than print. Once you see how a log record travels, the confusing bugs (nothing appears, everything appears twice) become easy to fix.

Why not print?

print writes text to stdout and that is all. A log call creates a record that carries a level, a timestamp, the logger's name, the source line and any exception, and the application decides what to do with it. That separation gives you:

  • Levels. DEBUG, INFO, WARNING, ERROR, CRITICAL. You can run at WARNING in production and switch to DEBUG for one noisy module without touching its code.
  • Destinations. The same call can go to the console, a file, or a log collector.
  • Context for free. Time, module, line number and traceback are added by the formatter, not typed by you.
  • Silence by default for libraries. A library can log freely and stays quiet unless the application asks to hear it.

print is still fine for a script's actual output, the thing the user asked for. Diagnostics belong in logs.

Python
import loggingimport sys logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)-8s %(name)s: %(message)s", datefmt="%H:%M:%S", stream=sys.stdout, # the default is stderr; stdout keeps this page's output in order force=True, # replace any earlier setup (other examples on this page run first)) log = logging.getLogger("shop.orders") log.debug("cart contents: %s", ["pen", "pad"]) # below INFO: droppedlog.info("order %s placed", 1042)log.warning("stock low for %s", "pen")log.error("payment failed for order %s", 1043)
Output
Press Run (⌘ Enter) to see what happens.

logging.getLogger(name) returns the same logger object every time for the same name. In real modules you write log = logging.getLogger(__name__) at the top, so the logger's name is the module's dotted path, like shop.orders.

The pieces and the path of a record

Four kinds of object do the work:

  • Loggers are what your code calls. They form a tree by dotted name: shop.orders is a child of shop, which is a child of the root logger.
  • Handlers send records somewhere: StreamHandler (stderr or stdout), FileHandler, RotatingFileHandler, and others. A logger can have several.
  • Formatters turn a record into text, using fields like %(asctime)s, %(name)s, %(levelname)s, %(message)s.
  • Filters can drop a record or add fields to it. They attach to loggers or handlers.
What happens on log.info(...)
log.info(): shop.orderslog.info()shop.ordersLevel check: effective levelLevel checkeffective levelLogRecord: + logger filtersLogRecord+ logger filtersOwn handlers: level, filters, formatOwn handlerslevel, filters, formatParent: shop: its handlersParent: shopits handlersRoot logger: basicConfig handlerRoot loggerbasicConfig handlerstderr / file: formatted linestderr / fileformatted linepassespropagatepropagate

The first and cheapest check: is INFO at or above the logger's effective level? If the logger has no level set, it uses the nearest ancestor's. If the check fails, nothing else happens.

1/5

Two details in that path surprise even experienced developers. First, the level check happens once, on the logger you called. If store.payments is set to DEBUG and its parent store is set to ERROR, debug records from store.payments still reach the root's handlers. Second, filters on a logger only see records logged directly to that logger. To filter everything, put the filter on the handler.

Python
import loggingimport sys logging.basicConfig(level=logging.WARNING, stream=sys.stdout, force=True, format="%(levelname)-7s %(name)-14s %(message)s") logging.getLogger("store").setLevel(logging.ERROR)logging.getLogger("store.payments").setLevel(logging.DEBUG) for name in ["store", "store.orders", "store.payments", "other"]: lg = logging.getLogger(name) print(f"{name:14} effective level = {logging.getLevelName(lg.getEffectiveLevel())}") logging.getLogger("store.orders").warning("dropped: store.orders inherits ERROR")logging.getLogger("store.payments").debug("shown: its own level is DEBUG")logging.getLogger("other").warning("shown: inherits WARNING from root")
Output
Press Run (⌘ Enter) to see what happens.

Configure once, at the entry point

The rule that keeps logging sane: library and module code only creates loggers and calls them. The application's entry point configures handlers and levels, once. That is your main(), your web app's startup, or your test setup.

For scripts, logging.basicConfig(...) is enough. It adds one handler to the root logger. It does nothing at all if the root already has handlers, which is a common source of confusion: if any code logged or configured before your call, your format and level are silently ignored. force=True (Python 3.8+) removes the existing handlers first. For services, logging.config.dictConfig describes loggers, handlers and formatters in one dict; you can see a full example in Logging and observability.

If you write a library, never call basicConfig and never add a real handler. Add only a NullHandler to your top-level logger, so the library is silent unless the application configures logging:

src/payments_sdk/__init__.py
import logging
 
logging.getLogger(__name__).addHandler(logging.NullHandler())

Without any configuration, Python does print WARNING and above to stderr, through a fallback called the last resort handler, with just the message and no format. That is why a warning shows up and your info call does not: the root logger's default level is WARNING.

Predict the outputPython

What does this print?

import logging
log = logging.getLogger("app")
log.info("starting")
log.warning("disk at 91%")
log.error("disk full")
Need a nudge? Hints walk you through it.

Pass arguments, not f-strings

Write log.info("user %s logged in", user_id), not log.info(f"user {user_id} logged in"). There are two reasons:

  1. Cost. With arguments, the string is only built if the record is emitted. A debug call in a hot loop costs almost nothing when debug is off. The f-string is built every time.
  2. Grouping. Error trackers like Sentry and log tools group records by the message template. "user %s logged in" is one group with many occurrences. A thousand f-strings are a thousand unique messages.

The arguments themselves are still evaluated. log.debug("%s", expensive()) calls expensive() even when debug is off. For that case, guard it with if log.isEnabledFor(logging.DEBUG):.

Python
import loggingimport sys logging.basicConfig(level=logging.INFO, stream=sys.stdout, force=True)log = logging.getLogger("perf") class Costly: renders = 0 def __str__(self): Costly.renders += 1 return "big object" obj = Costly()for _ in range(1000): log.debug("state: %s", obj) # lazy: never renderedprint("lazy renders:", Costly.renders) for _ in range(1000): log.debug(f"state: {obj}") # eager: rendered every timeprint("f-string renders:", Costly.renders)
Output
Press Run (⌘ Enter) to see what happens.

Logging exceptions properly

Inside an except block, use log.exception("message"). It logs at ERROR and appends the full traceback. For another level, pass exc_info=True, as in log.warning("retrying", exc_info=True). stack_info=True adds the current call stack even when there is no exception, which helps when you want to know who called a function.

Python
import loggingimport sys logging.basicConfig(level=logging.INFO, stream=sys.stdout, force=True, format="%(levelname)s %(name)s: %(message)s")log = logging.getLogger("billing") def charge(amount): return 100 / amount try: charge(0)except ZeroDivisionError: log.exception("charge failed for amount=%s", 0)
Output
Press Run (⌘ Enter) to see what happens.

One rule prevents a lot of noise: log an exception or re-raise it, not both. If every layer catches, logs and re-raises, one failure produces five tracebacks and nobody can tell how many incidents there were. Log at the boundary that handles the error (the request handler, the job runner), and let lower layers raise or add context with raise ... from as you saw in Errors and Exceptions.

Adding context: extra, adapters and request ids

A line like payment failed is useless without knowing which order and which request. extra={"order_id": 1043} attaches fields to the record. The formatter can print them (%(order_id)s), and a JSON formatter turns them into searchable fields. The keys must not clash with built-in record attributes: extra={"name": ...} raises a KeyError.

logging.LoggerAdapter wraps a logger and adds the same extra to every call, which suits a per-job or per-connection logger.

For web apps the standard pattern is a request id that appears on every line logged during that request, from any module. Passing it down through every function would be absurd. Instead, store it in a contextvars.ContextVar (each request or asyncio task sees its own value) and add a filter on the handler that copies it onto every record.

Python
import contextvarsimport loggingimport sys request_id = contextvars.ContextVar("request_id", default="-") class RequestIdFilter(logging.Filter): def filter(self, record): record.request_id = request_id.get() return True # keep the record handler = logging.StreamHandler(sys.stdout)handler.addFilter(RequestIdFilter()) # on the handler, so it sees every recordhandler.setFormatter(logging.Formatter("[%(request_id)s] %(name)s: %(message)s"))logging.basicConfig(level=logging.INFO, handlers=[handler], force=True) orders = logging.getLogger("api.orders")payments = logging.getLogger("api.payments") def handle(rid, order_id): token = request_id.set(rid) try: orders.info("placing order %s", order_id) payments.info("charging card", extra={"order_id": order_id}) finally: request_id.reset(token) handle("req-7f3a", 1042)handle("req-91bc", 1043)orders.info("outside any request")
Output
Press Run (⌘ Enter) to see what happens.

The bugs everyone hits

Every line appears twice. A handler was added to a child logger (often by a library or a copied snippet) and the record also propagates to the root's handler. Or a setup function that calls addHandler ran twice, which is common in notebooks and test suites. Fix it by configuring handlers only on the root, or set propagate = False on the logger that has its own handler.

Python
import loggingimport sys logging.basicConfig(level=logging.INFO, stream=sys.stdout, force=True, format="root handler | %(message)s") log = logging.getLogger("worker")log.handlers.clear() # so re-running this block starts cleanown = logging.StreamHandler(sys.stdout)own.setFormatter(logging.Formatter("worker handler | %(message)s"))log.addHandler(own) log.info("job started") # printed twice log.propagate = Falselog.info("job finished") # printed oncelog.propagate = True
Output
Press Run (⌘ Enter) to see what happens.

Nothing appears. The root level is still WARNING, or basicConfig was a no-op because something configured the root first. Check logging.getLogger().handlers and getEffectiveLevel() before guessing.

A library floods your output. Raise only that library's level: logging.getLogger("urllib3").setLevel(logging.WARNING). This is exactly why loggers are named by module.

Secrets in logs. Logs are copied to more places, and kept longer, than your database. Never log passwords, tokens, full card numbers, or whole request bodies and headers (Authorization lives there). Log ids, not personal data. A redaction filter on the handler is a good safety net, but the habit of not logging the object in the first place matters more.

Quick check
After adding a StreamHandler to the logger app.db, every database log line shows up twice. The root logger also has a handler from basicConfig. What is the cleanest fix?
Need a nudge? A hint rules out a wrong answer.

Threads, processes and files

The logging module is thread-safe: each handler holds a lock while it writes, so lines from different threads do not interleave mid-line. It is not safe for several processes writing the same file, which happens with multiprocessing or several web workers. Lines get mixed, and RotatingFileHandler rotations collide.

The standard answer is a queue. Each thread or process uses a cheap QueueHandler that only puts the record on a queue. One QueueListener takes records off and passes them to the real handlers. It also helps in async services, because a slow handler (a network call to a log service) no longer blocks the code that logs.

import logging
import logging.handlers
import queue
 
log_queue = queue.Queue()
file_handler = logging.handlers.RotatingFileHandler(
    "app.log", maxBytes=10_000_000, backupCount=5, encoding="utf-8"
)
file_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s"))
 
listener = logging.handlers.QueueListener(log_queue, file_handler)
listener.start()                       # a background thread does the slow writes
 
root = logging.getLogger()
root.setLevel(logging.INFO)
root.addHandler(logging.handlers.QueueHandler(log_queue))
 
try:
    run_app()
finally:
    listener.stop()                    # flushes what is left on the queue

For multiple processes, use a multiprocessing.Queue (or a Manager().Queue()) in the same pattern. Since Python 3.12, dictConfig can set up a QueueHandler with its listener for you; check the logging cookbook in the official docs for the current form. In containers you usually skip files entirely: write to stdout and let the platform collect it.

Where production logging goes next

Everything here produces text lines. In production you will want structured logs: one JSON object per line, so tools can filter on request_id or status. You get there with a JSON formatter on the same handler, or with a library like structlog, and you connect logs to traces with OpenTelemetry. Logging and observability covers that layer. The foundation does not change: named loggers, configured once, with context attached to records rather than baked into strings.

Match the pairs0/5 matched

Match each piece of the logging system to its job.

Choose an item, then its match on the other side.
Put it in order5 steps

Put these stages of a log.info(...) call in the order they happen.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Debug logging is off. Which call still does expensive work?
Need a nudge? A hint rules out a wrong answer.
Key terms
logger
A named object your code calls. Names are dotted, so loggers form a tree under the root logger.
handler
An object that sends log records to a destination such as a stream, a file or a queue.
effective level
A logger's own level, or the nearest ancestor's if it has none. Records below it are dropped.
propagation
Passing a record up to each ancestor logger's handlers. Stopped with propagate = False.
basicConfig
A one-call setup that adds a handler to the root logger, and does nothing if the root already has handlers unless force=True.
NullHandler
A handler that discards records. Libraries add it so they stay silent by default.
QueueHandler
A handler that only puts records on a queue, for a QueueListener to write from one place.