Lesson · Logging & Diagnostics
Logging
65 min readLogging
Logging records structured operational events without coupling diagnostics to `print`. Logger hierarchy, levels, handlers, formatting, and exception information let applications route different signals to different destinations.
Learning goals
- Configure the root logger with
basicConfigand explain whylevel=logging.INFOdecides which records survive and which are dropped. - Create a named logger with
logging.getLogger(__name__)and describe how its dotted name places it in the logger hierarchy. - Route one logger's records to several destinations with handlers, and shape each line with a formatter template like
"%(levelname)s %(name)s: %(message)s". - Read the five levels from DEBUG to CRITICAL and predict which calls are emitted at a given threshold.
- Capture a traceback inside an
exceptblock withlog.exceptionand say what differs fromlog.error.
Mental model
A record is offered to the logger's own handlers first and then to the handlers of each ancestor, so a duplicated line usually means two handlers in that chain rather than a bug in the call. The threshold decides whether a record leaves the call site at all, and the formatter decides what a surviving record looks like.
Mental model
read it top to bottom
log.info("application started") a call on a named Logger
↓ level check INFO must pass the logger's effective level
↓ the record travels up handlers on each ancestor may emit it too
handlers console stream, file, other destinations
↓ formatter "%(levelname)s %(name)s: %(message)s"
output lineCore idea
Two knobs do most of the work in logging: the level threshold decides whether a record is emitted, and the handler plus formatter decide where it goes and how it reads. The unit of organization is the named logger, because logging.getLogger(__name__) gives each module a handle into a shared hierarchy whose verbosity can be tuned without editing call sites. Keeping message, severity and destination separate is what lets the same call work in a REPL and in production.
logging
logging is the standard library's framework for emitting diagnostic events. Code calls methods such as info, warning and exception on a logger, and each call builds a record that flows to the handlers attached to that logger and its ancestors. A module-level call like logging.info(...) goes through the root logger, which is why application modules normally create a named logger with logging.getLogger(__name__).
Levels
The five levels name the severity a record carries: DEBUG, INFO, WARNING, ERROR and CRITICAL, backed by the numbers 10, 20, 30, 40 and 50. A logger has an effective level, and a call is emitted only when its severity is at or above that threshold, so raising the threshold silences output without changing any call site. Handlers can apply a second threshold of their own when they route records.
Loggers
Loggers are the named channels records travel through, created with logging.getLogger(...). The dotted name forms a hierarchy, so a logger called a.b is a child of a and inherits its effective level and handlers until it is configured differently. Passing __name__ gives each module its own separately controllable channel.
Handlers
Handlers are the destinations attached to a logger, such as StreamHandler for a stream and FileHandler for a file. A logger can hold several at once, each with its own level and formatter, so one record can print in full to the console and be written at ERROR or higher to a file.
Formatters
Formatters turn a LogRecord into the text a handler writes, using a template such as %(levelname)s %(name)s: %(message)s. Named fields read attributes from the record, such as levelname, name and asctime, and a handler with no formatter falls back to the bare message.
Module-level loggers
In Logging, Module-level loggers names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
Exceptions and stack traces
In Logging, Exceptions and stack traces names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
Walkthrough
basicConfig(level=logging.INFO, format=...)installs a stream handler on the root logger and sets the threshold, solog.info("application started")prints while alog.debug(...)added beside it would be dropped without complaint.log = logging.getLogger(__name__)returns a logger named after the module, and%(name)sin the format renders that name on every line next to%(levelname)s.log.exception("calculation failed")runs insideexcept ZeroDivisionError, so it emits at ERROR level and appends the active traceback to the message;log.error(...)in the same spot would keep the text but lose the stack.- Predict before running: which calls produce output, what
%(name)sexpands to when the file is run directly, and whether the failure line includes theZeroDivisionErrortraceback.
Experiments to try
- Lower the threshold with
level=logging.DEBUG, addlog.debug("starting")above the INFO call, and confirm that the threshold alone controls visibility. - Attach a
FileHandler("app.log")alongside the console handler, run the snippet, then check which destination received the ERROR record and whether the traceback was written too. - Change the format string to
"%(asctime)s %(levelname)s %(name)s %(message)s"and identify which pieces come from the template and which from the record. - Replace
log.exceptionwithlog.error("calculation failed", exc_info=True)and diff the outputs; the two should match, so decide which spelling reads better.
Common mistakes
- Calling
printfor diagnostics: a print carries no level, name or destination, so production noise cannot be silenced or routed without editing every call site. - Calling
basicConfigwhen the root logger already has a handler: the second configuration is silently ignored, because basicConfig only takes effect while the root logger has no handlers, unlessforce=Trueis passed. - Logging through the root logger in shared code:
logging.info(...)tags records withrootand exposes them to global configuration, whilelogging.getLogger(__name__)keeps each module's output separately controllable. - Formatting messages eagerly:
log.debug(f"value {x}")interpolates the string before the threshold check, whilelog.debug("value %s", x)leaves interpolation to the logging call, which only formats records that are emitted.
Practice: Easy
- Run the worked example as
app.py; then comment outbasicConfigand run again. Note that the INFO line disappears while the ERROR record still reaches stderr through the handler of last resort, and explain the difference. - In the REPL, create
logging.getLogger("a")andlogging.getLogger("a.b"), callsetLevel(logging.CRITICAL)ona, and checka.b.isEnabledFor(logging.WARNING)to show the child inheriting the parent's threshold. - Add one
log.debug("starting")call to the example and run it once withlevel=logging.INFOand once withlevel=logging.DEBUG; record which run shows the line.
Practice: Medium
- Extend the example into a
configure()function that attaches aStreamHandlerat INFO and aFileHandler("app.log")at ERROR, then log one INFO and one ERROR record and show which destination each reaches. - Move the logging calls into a second module
calc.pythat useslogging.getLogger(__name__), import it from a smallapp.pythat configures logging, and confirm the log lines now namecalcinstead of__main__. - Reproduce the
basicConfigno-op: configure logging twice with different formats, observe that the second call changes nothing, then re-run withforce=Trueand explain what the flag did.
Practice: Hard
- Design a
configure_logging(verbose)helper for a small CLI: in verbose mode your package logger runs at DEBUG while everything else stays at WARNING; in normal mode your package runs at INFO. Name the loggers and handlers it touches, implement it, and verify both modes with one DEBUG and one INFO call. - Build a logging failure lab: trigger a duplicate output through a handler plus propagation to root, a lost traceback from
log.errorcalled outside anexceptblock, and a silentlog.debugunder a higher threshold. Explain the mechanism behind each result. - Capture the example's records in a test with
unittest'sassertLogs, asserting on the level and message of the failure record, and show what the test cannot observe if it reads printed output instead of records.
Lesson checklist
- I can trace a record from the log call through the level check, the handler chain and the formatter.
- I can configure
getLogger(__name__)with a level, a handler and a format string, and predict which calls produce output. - I can capture a traceback with
log.exceptionand explain what goes missing withlog.error. - I can recognize the handlers-already-configured trap and apply
force=Truedeliberately.
Remember
Two knobs do most of the work in logging: the level threshold decides whether a record is emitted, and the handlers plus formatter decide where it goes and how it reads. Give every module a logger through `getLogger(__name__)`, configure the destinations once, and keep `log.exception` inside `except` blocks so failures arrive with their tracebacks.
Interview angles
What is the main purpose of **logging**?+
logging is the standard library's framework for emitting diagnostic events: calls on a logger build records that flow to the handlers on that logger and its ancestors. Because a module-level call goes through the root logger, application modules normally create their own with logging.getLogger(__name__).
What should you pay attention to when using **Levels**?+
Levels are the named severities DEBUG, INFO, WARNING, ERROR and CRITICAL. A call is emitted only when its severity is at or above the logger's effective level, which is why the example's level=logging.INFO keeps the INFO and ERROR lines but would drop any DEBUG call.
How does **Loggers** fit into this lesson?+
getLogger(__name__) returns a named logger whose dotted name forms a hierarchy: a.b is a child of a and inherits its effective level and handlers. Passing __name__ gives each module a channel that can be tuned up or down without editing call sites.
Why does a second `logging.basicConfig(...)` call often change nothing, and what fixes it?+
basicConfig only configures the root logger while it has no handlers; once any handler exists (including one installed by another library), the call is a no-op unless you pass force=True.