Skip to the solution
MediumBackend12 min read

How does the logging module work?

1.0k views

The problem

Question presented to candidate: "Explain how Python's logging module works. What are loggers, handlers and formatters, how does a log call decide whether and where to output something, and how would you set up logging for an application versus a library?"

What a strong answer should cover:

  • Loggers come from logging.getLogger(__name__) and form a tree by dotted name under the root logger; each has a level, and an unset level (NOTSET) inherits the nearest ancestor's (the root defaults to WARNING)
  • The flow of a record: logger level check, logger filters, then every handler on that logger and, while propagate is true, on each ancestor; each handler has its own level, filters and formatter
  • Handlers decide the destination (StreamHandler, FileHandler, RotatingFileHandler, QueueHandler), formatters the text (%(asctime)s %(levelname)s %(name)s %(message)s)
  • Use %-style arguments (log.info("user %s", uid)) so formatting is skipped when the record is filtered out; log.exception() inside except adds the traceback; extra= or a LoggerAdapter add context fields
  • Configuration: basicConfig once at the application entry point (a no-op if the root already has handlers, unless force=True, added in 3.8), or dictConfig for real apps; libraries only call getLogger and add a NullHandler, never configure the root
  • Pitfalls: duplicate lines from handlers on both a child and the root, disable_existing_loggers defaulting to true in dictConfig, and the last-resort handler that prints WARNING and above to stderr when nothing is configured

Code / implementation expected: Optional โ€” configure a handler and formatter, show a module logger inheriting a level, and one propagation or exception() example.

  • logging
  • stdlib

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonLoggers, levels, handlers, formatters, exception() and propagation
PythonbasicConfig, the last-resort handler, NullHandler, dictConfig, filters and context

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 48 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is the @property decorator?

Continue