Advanced Python / Logging

Advanced Python / Logging#

  1. What are the five standard log levels in Python’s logging module? 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

  2. 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 any logging.debug() or logging.info() calls made before any configuration is applied are silently discarded — they produce no output at all. A new program that relies on logging.info() for progress messages will see nothing unless it first lowers the threshold with basicConfig(level=logging.DEBUG) or similar.

  3. 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 calls basicConfig() attaches a handler to the root logger; every subsequent cell that calls basicConfig() 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=True removes all existing handlers from the root logger before applying the new configuration.

  4. What is the difference between attaching a Formatter to 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] message format on the console and a verbose timestamp | name | level | file:line | message format 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).

  5. Explain log record propagation. What does logger.propagate = False do, 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 = False stops 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)

  6. What is a RotatingFileHandler and why is it preferred over a plain FileHandler in production applications?

    RotatingFileHandler writes 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 to app.log.1 (pushing any existing .1 to .2, etc., up to backupCount files) and a fresh app.log is started. This keeps disk usage bounded.

    A plain FileHandler writes 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 (or TimedRotatingFileHandler for time-based rotation) prevents this by automatically managing log file sizes.

  7. How does logger.exception() differ from logger.error()? Why is it preferable inside an except block?

    logger.exception(msg) is identical to logger.error(msg, exc_info=True). Both log at ERROR level, but exception() automatically captures the current exception information (type, value, and full traceback) and appends it to the log record.

    Inside an except block the current exception is available via sys.exc_info(). Calling logger.exception() captures it without any extra arguments. A bare logger.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
    
  8. What is the purpose of the extra parameter when calling a logging method? Give an example where using extra is more appropriate than embedding context directly in the message string.

    The extra parameter attaches a dictionary of arbitrary fields to the LogRecord object. 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 extra rather 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})
    
  9. What advantage does logging.config.dictConfig() offer over logging.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 addHandler calls

    • Environment-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.

  10. Why should library authors use logging.NullHandler() and avoid calling basicConfig() 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 NullHandler to 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())