Python Tutorial 0/52 lessons ~6 min read Lesson 42

    Logging

    Use the stdlib logging module — never print() in production.

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Use the stdlib logging module — never print() in production. Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.

    Understanding the topic

    Core concepts to understand:

    • Get a logger per module: logging.getLogger(__name__).
    • Configure once at app entry (basicConfig or dictConfig).
    • Structured logs (JSON) for production.
    • Use logger.exception() in except blocks.

    Syntax reference

    Visual flow / code:

    python
    import logging
    logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s %(message)s",
    )
    logger = logging.getLogger(__name__)
    try:
    risky_op()
    except Exception:
    logger.exception("risky_op failed") # logs traceback
    logger.info("user %s logged in", user_id)

    Execution workflow

    1Logging Workflow
    1 / 4

    Get a logger per module

    logging.getLogger(__name__).

    Real-world use

    Production stacks ship JSON logs to ELK/Loki/Datadog. Libraries like structlog and loguru are popular alternatives.

    Best practices

    • Never print() in libraries/services.
    • Log at INFO for business events, DEBUG for diagnostics.
    • Use structured logging in prod.

    Common mistakes

    • String-formatting in log calls: use %s, not f-strings, to avoid evaluating when level filters out.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionLogger vs print?+

    Answer

    print writes text to stdout with no structure. The logging module adds levels (DEBUG to CRITICAL), timestamps, logger names, configurable handlers and formatters, and the ability to route output to files or services and filter by severity without changing code. Libraries should use logging.getLogger(__name__) and leave configuration to the application.

    Follow-up

    Why should libraries not call basicConfig?
    2IntermediateQuestionWhat's structured logging?+

    Answer

    Structured logging emits each event as machine-readable key-value data, usually JSON, such as {"event": "payment_failed", "user_id": 42}, instead of a free-text sentence. That makes logs searchable and aggregatable in tools like Elasticsearch or Loki. In Python you can use a JSON formatter, the extra argument, or libraries such as structlog.

    Follow-up

    How would you attach a request ID to every log line?
    3BeginnerQuestionlogger.exception vs error?+

    Answer

    Both log at ERROR level, but logger.exception(msg) also attaches the current exception's traceback, as if you had passed exc_info=True. It should be called from inside an except block. Use logger.error for errors with no active exception, or pass exc_info explicitly to get a traceback at a different level.

    Follow-up

    How do you log a traceback at WARNING level?

    Summary

    In summary: Logging > print, always. Structured = searchable + parseable.

    Ready to mark this lesson complete?Track your journey across the entire course.