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.
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 atWARNINGin production and switch toDEBUGfor 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.
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.ordersis a child ofshop, 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.
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.
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.
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:
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.
What does this print?
import logging
log = logging.getLogger("app")
log.info("starting")
log.warning("disk at 91%")
log.error("disk full")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:
- Cost. With arguments, the string is only built if the record is emitted. A
debugcall in a hot loop costs almost nothing when debug is off. The f-string is built every time. - 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):.
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.
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.
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.
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.
app.db, every database log line shows up twice. The root logger also has a handler from basicConfig. What is the cleanest fix?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 queueFor 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 each piece of the logging system to its job.
Put these stages of a log.info(...) call in the order they happen.
- Tap the steps below in the right order.
- 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.