Advanced Python / Logging#
What are the five standard log levels in Python’s
loggingmodule? List them in order from lowest to highest severity and describe when each should be used.In ascending order of severity:
Level
Use when…
DEBUG(10)Recording fine-grained internal state useful only while diagnosing a specific problem during development or debugging
INFO(20)Confirming that the program is progressing normally (e.g., “server started”, “file loaded”, “job complete”)
WARNING(30)Something unexpected occurred but the program can continue; worth noting for later investigation
ERROR(40)A specific operation failed; the program can keep running but a feature or request did not complete
CRITICAL(50)A severe failure that may cause the program to abort or that requires immediate attention
What is the default log level of the root logger, and why does this matter for a new Python program that has not called
basicConfig()?The root logger’s default level is
WARNING(30). This means anylogging.debug()orlogging.info()calls made before any configuration is applied are silently discarded — they produce no output at all. A new program that relies onlogging.info()for progress messages will see nothing unless it first lowers the threshold withbasicConfig(level=logging.DEBUG)or similar.Why is
logging.basicConfig()sometimes a no-op? How do you force it to reconfigure the root logger in a Jupyter notebook environment?basicConfig()checks whether the root logger already has any handlers attached. If it does, the call does nothing and returns immediately. In a Jupyter notebook, executing one cell that callsbasicConfig()attaches a handler to the root logger; every subsequent cell that callsbasicConfig()again will silently do nothing unless the existing handler is removed first.The fix is to pass
force=True(available since Python 3.8):logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s", force=True)
force=Trueremoves all existing handlers from the root logger before applying the new configuration.What is the difference between attaching a
Formatterto a Logger versus attaching it to a Handler? Why does the distinction matter?Formatters are attached to Handlers, not to Loggers. This design allows a single logger to write records to multiple destinations with different layouts — for example, a concise
[WARNING] messageformat on the console and a verbosetimestamp | name | level | file:line | messageformat in the file, while the underlying log calls and logger configuration remain unchanged.If formatters were attached to loggers you could only have one format per logger, making it impossible to tailor the layout to different audiences (a developer reading a file versus a dashboard alert).
Explain log record propagation. What does
logger.propagate = Falsedo, and when would you use it?When a named logger emits a record, by default it hands the record up to its parent logger, which in turn hands it to its parent, and so on until the root logger is reached. This is called propagation. It means you only need to attach handlers to the root (or to a high-level application logger) and all descendants will automatically send their records there.
Setting
logger.propagate = Falsestops this upward pass at that logger. The record is processed only by the handlers attached directly to that logger and goes no further.Common uses:
A logger that writes to its own dedicated file and should not also appear in the application’s main log
Silencing a noisy third-party library logger that has been given a
NullHandler(so records go nowhere instead of reaching the root handler)
What is a
RotatingFileHandlerand why is it preferred over a plainFileHandlerin production applications?RotatingFileHandlerwrites log records to a file but caps the file at a configurable maximum byte size (maxBytes). When the file reaches that size, it is renamed toapp.log.1(pushing any existing.1to.2, etc., up tobackupCountfiles) and a freshapp.logis started. This keeps disk usage bounded.A plain
FileHandlerwrites to a single file that grows without bound. In a long-running production service this will eventually consume all available disk space, either crashing the service or filling the disk for other processes.RotatingFileHandler(orTimedRotatingFileHandlerfor time-based rotation) prevents this by automatically managing log file sizes.How does
logger.exception()differ fromlogger.error()? Why is it preferable inside anexceptblock?logger.exception(msg)is identical tologger.error(msg, exc_info=True). Both log atERRORlevel, butexception()automatically captures the current exception information (type, value, and full traceback) and appends it to the log record.Inside an
exceptblock the current exception is available viasys.exc_info(). Callinglogger.exception()captures it without any extra arguments. A barelogger.error()in the same place produces only the message text — the traceback is lost. Without the traceback it is often impossible to locate or diagnose a production error.try: result = risky_operation() except ValueError: logger.exception("Operation failed") # includes traceback # vs. logger.error("Operation failed") # message only — traceback lost
What is the purpose of the
extraparameter when calling a logging method? Give an example where usingextrais more appropriate than embedding context directly in the message string.The
extraparameter attaches a dictionary of arbitrary fields to theLogRecordobject. Those fields can be referenced in the formatter’s format string, stored in structured log systems, or read by custom handlers — without changing the log message itself.It is more appropriate than embedding context in the message string when:
The context will be queried or filtered by a log aggregation tool (Elasticsearch, Splunk, Datadog) — structured fields are far easier to query than free text
The same context applies to many log calls within a function (attach it once to
extrarather than repeating it in every message string)
# Less useful: context buried in free text logger.info(f"Order submitted: ticker=AAPL user=U-4821 shares=50") # Better: context as structured fields logger.info("Order submitted", extra={"ticker": "AAPL", "user_id": "U-4821", "shares": 50})
What advantage does
logging.config.dictConfig()offer overlogging.basicConfig()for a production application?dictConfig()accepts a complete configuration as a plain Python dictionary, separating configuration from code. This enables:External configuration — load the dictionary from a JSON or YAML file so operations teams can change log levels or destinations without modifying or redeploying code
Multiple loggers and handlers — configure any number of named loggers, each with their own level and set of handlers, in a single call
Reproducibility — the full configuration is captured in one place rather than scattered across multiple
addHandlercallsEnvironment-specific profiles — maintain separate configuration files for development (verbose, console) and production (INFO, rotating file + alerting)
basicConfig()is a convenience function that can configure only the root logger with a single handler and is not designed to express complex multi-handler, multi-logger configurations.Why should library authors use
logging.NullHandler()and avoid callingbasicConfig()inside their library code?A library is imported into an application that has its own logging configuration. If a library calls
basicConfig(), it silently attaches a handler to the root logger, which may:Override or interfere with the application’s existing configuration
Cause library log records to appear in the application’s output unexpectedly
Prevent
basicConfig()from working for the application (since it becomes a no-op once handlers exist)
The convention for library authors is to attach a
NullHandlerto the library’s top-level logger. This satisfies the logging system’s requirement that a logger have at least one handler (preventing “No handlers could be found” warnings) while discarding all records by default. The application that imports the library can then attach real handlers if it wants library output.# In mylib/__init__.py import logging logging.getLogger(__name__).addHandler(logging.NullHandler())