Standard Library

Logging

logging records operational events without using print as infrastructure.

A logger name records which part of the program produced the event. The handler and formatter choose where and how the event is shown.

Source

import logging
import sys

logger = logging.getLogger("example.worker")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
parts = ["%(levelname)s", "%(name)s", "%(message)s"]
formatter = logging.Formatter(":".join(parts))
handler.setFormatter(formatter)
logger.handlers[:] = [handler]
logger.propagate = False

logger.debug("hidden detail")
logger.info("service started")
logger.warning("disk almost full")

Output

INFO:example.worker:service started
WARNING:example.worker:disk almost full
CRITICAL50ERROR40WARNING30INFO20DEBUG10
Five severity levels; the logger's configured threshold drops everything below it.

Levels are thresholds. Raising the handler level to WARNING suppresses later INFO records without changing the call sites.

Source

import logging
import sys

logger = logging.getLogger("example.worker")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.WARNING)
parts = ["%(levelname)s", "%(name)s", "%(message)s"]
formatter = logging.Formatter(":".join(parts))
handler.setFormatter(formatter)
logger.handlers[:] = [handler]
logger.propagate = False

logger.info("hidden after threshold change")
logger.error("write failed")

Output

ERROR:example.worker:write failed

Notes

See also

Run the complete example

Example code

Expected output

INFO:example.worker:service started
WARNING:example.worker:disk almost full
ERROR:example.worker:write failed

Execution time appears here after you run the example.