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
    Foundation builder

    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

    Step 1

    Get a logger per module: logging.getLogger(__name__).

    Apply this step while implementing logging in real code.

    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.

    Hands-on exercise

    Interview preparation — practice these questions:

    • Logger vs print?
    • What's structured logging?
    • logger.exception vs error?

    Summary

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

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