Sub topic 16
Practical guidelines and common pitfalls
This chapter pulls together the earlier material into working rules. It assumes you know loggers, handlers, formatters, levels, propagation, and dictConfig from the previous chapters, and that you can read a short Python script. Most logging bugs come from a few causes: configuring in the wrong place, getting duplicate output, losing messages, or doing expensive work for messages nobody reads.
Rules that prevent most problems
Create one logger per module
Put logger = logging.getLogger(__name__) at the top of each module. The name follows your package layout, so myapp.db.pool is automatically a child of myapp.db. You can then tune levels per package without changing code.
Avoid the module-level functions logging.info(), logging.warning(), and so on in application modules. They log through the root logger, so you lose the module name. If the root logger has no handlers, they also call basicConfig() for you as a side effect, and that is rarely what you want.
Configure logging once, at the entry point
Only the application's entry point (main(), a __main__ block, or the WSGI/ASGI startup code) should add handlers, set levels, or call basicConfig or dictConfig. Modules import and use loggers but never configure them.
import logging
logger = logging.getLogger(__name__)
def process(items):
logger.info("Processing %d items", len(items))
for item in items:
logger.debug("Item: %r", item)
def main():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
process(["a", "b"])
if __name__ == "__main__":
main()Library code follows a stricter rule. It never configures output. It only attaches a NullHandler to its top-level logger, as covered in the library chapter.
Pass arguments to the logger instead of formatting messages yourself
logger.info("User %s logged in from %s", user, ip) # preferred
logger.info(f"User {user} logged in from {ip}") # formats even if INFO is offWith %s arguments, the string is built only after the record passes the level check. Filters, formatters, and tools that group similar messages also see the original template and the separate arguments. Use %r when you want the repr(), which makes whitespace and empty strings visible.
If building an argument is itself expensive, guard it:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def expensive_dump(data):
return ", ".join(f"{k}={v}" for k, v in sorted(data.items()))
data = {"a": 1, "b": 2}
if logger.isEnabledFor(logging.DEBUG):
logger.debug("State: %s", expensive_dump(data))Without the guard, expensive_dump(data) runs on every call, even though the DEBUG record is then discarded.
Log exceptions with their traceback
Inside an except block, use logger.exception("what failed"). It logs at ERROR and appends the traceback. To keep another level, use logger.warning("...", exc_info=True). Do not write logger.error(str(e)). It throws away the traceback and often the exception type.
Log an exception at the place where you handle it, not at every layer it passes through. If you log and then re-raise at each layer, one failure produces many near-identical entries.
Choose levels by who needs to act
| Level | Use it for |
|---|---|
| DEBUG | Detail useful only while diagnosing a problem |
| INFO | Normal milestones: startup, a job finished, a request served |
| WARNING | Something unexpected happened but the program continues |
| ERROR | An operation failed |
| CRITICAL | The program cannot continue |
A common mistake is logging routine, expected conditions as WARNING. If an alert fires on every WARNING, people soon stop reading them.
Common pitfalls and their symptoms
| Symptom | Likely cause | Fix |
|---|---|---|
| Every line printed twice | A handler was added more than once, or a child logger has a handler and also propagates to the root handler | Configure once; set `propagate = False` or remove the duplicate handler |
| `basicConfig` seems ignored | The root logger already has handlers | Call it earlier, or pass `force=True` (Python 3.8+) |
| INFO messages never appear | The logger's effective level is WARNING (the root default) | Set the level on the logger or root |
| Level is right but a handler stays silent | The handler has its own, stricter level | Check both logger and handler levels |
| A library's logs vanish after configuration | `dictConfig` with `disable_existing_loggers` left at its default of `True` | Set it to `False` |
| Messages from a library appear unformatted on stderr | No handlers anywhere, so the last-resort handler prints WARNING and above | Configure logging in the application |
| `NoneType: None` appears after the message | `exc_info=True` or `logger.exception` used outside an `except` block | Call it only while handling an exception |
Duplicate output
Duplicates come from two places. The first is a function that adds a handler each time it runs:
import logging
def get_logger():
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
return logger
get_logger()
get_logger().info("hello") # printed twice: two handlers are attachedThe second is a logger that has its own handler while the root also has one:
import logging
logging.basicConfig(level=logging.INFO, format="root: %(message)s")
logger = logging.getLogger("myapp")
logger.addHandler(logging.StreamHandler())
logger.info("hello") # printed by both handlers
logger.propagate = False
logger.info("only once") # printed by the logger's own handler onlyThe simplest cure is the rule above: set up handlers in one place, once. Setting propagate = False is reasonable when a subsystem deliberately owns its output, such as an audit log with its own file.
Levels are checked at two points
A record must pass the logger's effective level when it is created. Then each handler that sees it applies its own level. A DEBUG file handler on a logger whose effective level is INFO will never receive DEBUG records. Set the logger to the lowest level any handler needs, and let handler levels narrow it down.
Remember also that propagation skips ancestor logger levels. A record that passed the child's check goes straight to the ancestors' handlers, and only those handlers' levels apply.
Where a message goes missing
When output is missing, walk this chart with logger.getEffectiveLevel(), logger.handlers, logger.propagate, and logger.disabled.
Safety and cost
- Do not log secrets. Passwords, tokens, API keys, and full card numbers must stay out of messages. Be careful when logging whole request bodies, headers, or
repr()of objects that hold credentials. A filter can redact known patterns, but not logging the data is safer. - Do not trust user text in the format string. Pass user input as an argument (
logger.info("name=%s", name)), never as the message template. - Keep volume bounded. Logging inside a tight loop at INFO can be slower than the work itself. Log a summary or sample instead. Use
RotatingFileHandlerorTimedRotatingFileHandler, or an external tool, so files do not fill the disk. - Do not let logging take down the program. By default, a handler that fails while emitting prints a traceback to stderr through
Handler.handleErrorand carries on. This is good for production. Do not setlogging.raiseExceptions = Falseto hide the problem. Fix the handler instead. - Keep slow destinations off the hot path. Network, database, and remote syslog handlers can block your request thread. Use
QueueHandlerwithQueueListener.
Processes and threads
Logging is thread-safe. Handlers take a lock while emitting, so threads can share loggers freely.
Separate processes are different. Several processes writing to the same file through FileHandler or RotatingFileHandler can interleave lines or corrupt a rotation. Either log to stderr or stdout and let the platform collect the output, or send records from workers to one process with a QueueHandler over a multiprocessing.Queue and a single QueueListener.
At exit, logging.shutdown() runs automatically and flushes handlers. Call it yourself only in unusual cases such as os._exit(), which skips it.
A short review checklist
- Each module uses
getLogger(__name__). - Only the entry point configures handlers and levels.
- Messages use
%sarguments, not f-strings. - Exceptions are logged once, with
logger.exceptionorexc_info=True. - Libraries add only a
NullHandler. - No secrets reach any handler.
- Files rotate, and slow handlers sit behind a queue.
Exercise
A script calls logging.basicConfig(level=logging.INFO). A module then does logger = logging.getLogger("app"); logger.addHandler(logging.StreamHandler()); logger.info("started"), and "started" appears twice on the console. Explain why, and give two ways to get a single line.
Show answer
The "app" logger has its own StreamHandler, and the record also propagates to the root logger, whose handler was created by basicConfig. Both write to stderr, so the line is printed twice. Fix 1: remove the extra handler in the module and let the root handler do the output. Fix 2: keep the handler and set logger.propagate = False, so the record is not passed to the root's handlers.
Exercise
What is wrong with logger.debug(f"Loaded {len(rows)} rows: {dump(rows)}") in a busy function, and how would you rewrite it?
Show answer
The f-string is evaluated, including the expensive dump(rows) call, on every call even when DEBUG is disabled. Rewrite it as logger.debug("Loaded %d rows", len(rows)). If the dump is needed, wrap it in if logger.isEnabledFor(logging.DEBUG): logger.debug("Rows: %s", dump(rows)).