Sub topic 16
Practical guidelines and common pitfalls
This chapter assumes you know loggers, handlers, formatters, levels, the logger hierarchy, and dictConfig from earlier chapters. It collects the habits that keep logging correct and cheap, and the mistakes that cause missing or duplicated output.
Guidelines
- Create one logger per module with
logging.getLogger(__name__). The dotted name places the module in the hierarchy automatically. - Configure logging once, at the application entry point. Libraries only add a
NullHandler. - Pass arguments to the logger and do not format the string yourself. The logger formats the message only if the record passes the level check.
- Use
logger.exceptioninsideexceptblocks so the traceback is kept. - Pick levels by audience. DEBUG is for developers, INFO for normal milestones, WARNING for unexpected but handled events, ERROR for failed operations, CRITICAL for failures that threaten the whole process.
- Never log secrets such as passwords, tokens, or full card numbers.
Pitfall 1: eager string formatting
An f-string is built before the logger is called, even when the message is discarded.
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
items = list(range(5))
# Bad: the string is built even though DEBUG is disabled
logger.debug(f"Items: {items}")
# Good: formatting happens only if the record is emitted
logger.debug("Items: %s", items)If computing an argument is itself expensive, guard it with if logger.isEnabledFor(logging.DEBUG):.
Pitfall 2: duplicate lines
A record propagates to the handlers of every ancestor. If you attach a handler to myapp and the root logger also has one, each message prints twice.
import logging
logging.basicConfig(level=logging.INFO) # root handler
logger = logging.getLogger("myapp")
logger.addHandler(logging.StreamHandler()) # second handler
logger.info("Printed twice")Fix this by attaching handlers only at the root, or by setting logger.propagate = False on the logger that owns its handlers. Calling addHandler inside a function that runs more than once causes the same symptom, because each call adds another handler.
Pitfall 3: missing output
The usual causes are listed below.
| Symptom | Likely cause |
|---|---|
| INFO messages never appear | The effective level is WARNING, the default for the root logger |
| `basicConfig` seems ignored | The root logger already had handlers, so the call did nothing |
| Library loggers go silent after configuring | `disable_existing_loggers` was left at its default of `True` in `dictConfig` |
| Records reach the logger but not the handler | The handler's own level is higher than the record's level |
Pitfall 4: logging exceptions incorrectly
Writing logger.error(e) records only the message text. Use logger.exception("Operation failed") in the handler, or logger.error("Operation failed", exc_info=True) elsewhere. Also avoid logging an exception and then re-raising it at every layer, since one failure then produces many traceback copies. Log it where you handle it.
Pitfall 5: configuration at import time
Calling basicConfig or adding handlers at the top level of a library module overrides the choices of the application. Keep configuration in a main() function or the entry script.
A sensible starting setup
import logging
def main():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)
try:
int("not a number")
except ValueError:
logger.exception("Could not parse input")
if __name__ == "__main__":
main()Exercise
A script prints every message twice. It calls logging.basicConfig(level=logging.INFO) and also creates logging.getLogger("app") with its own StreamHandler. Name two ways to fix it.
Show answer
Remove the extra handler from the "app" logger so the root handler handles everything, or set propagate = False on the "app" logger so its records do not reach the root handler.
Exercise
Why is logger.debug("Total: %s", total) preferred over logger.debug(f"Total: {total}")?
Show answer
With the argument form, the logger builds the string only if the record passes the level check. The f-string is built every time, even when DEBUG is disabled.