On this page
  1. logging
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Library vs. Application Pattern
  7. 2. Capturing Tracebacks Cleanly
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

logging

Prev: locale | Up: stdlib_module | Next: lzma
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — logging
Tags: #public #python3 #stdlib


Import

import logging

Overview

Hierarchical, configurable structured event logging with severity levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), pluggable handlers (console, rotating files, syslog), and formatters. Use logging instead of print() in any reusable library or long-running service so callers control verbosity and output destinations.

Quick Start

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)
logger.info("Service started on port %d", 8080)

Implementation Walkthrough

1. Library vs. Application Pattern

Libraries should only obtain a module logger (logging.getLogger(__name__)) and never call basicConfig(); applications configure handlers once at startup:

import logging
from logging.handlers import RotatingFileHandler

def configure_logging(log_file: str, level: int = logging.INFO) -> None:
    root = logging.getLogger()
    root.setLevel(level)
    fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")

    console = logging.StreamHandler()
    console.setFormatter(fmt)

    file_handler = RotatingFileHandler(log_file, maxBytes=1_000_000, backupCount=3, encoding="utf-8")
    file_handler.setFormatter(fmt)

    root.addHandler(console)
    root.addHandler(file_handler)

2. Capturing Tracebacks Cleanly

import logging

logger = logging.getLogger(__name__)
try:
    1 / 0
except ZeroDivisionError:
    logger.exception("Division failed for denominator=%s", 0)

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes