Skip to content
Python Basics: Recording Events with logging

Python Basics: Recording Events with logging

October 11, 2026

Python’s standard-library logging module records events with severity levels. A script can show important messages while keeping diagnostics quiet.

Use Python 3.12 or newer on Linux. Run each saved script separately to start a fresh Python process. The scripts create no data files.

See the default threshold

Save as demo_logging_1.py:

import logging

logging.info("Starting inventory check")
logging.warning("Only two notebooks remain")

Run:

python3 demo_logging_1.py

Output on standard error:

WARNING:root:Only two notebooks remain

The root logger starts at WARNING, so the INFO message is hidden. These module-level calls configure a handler automatically when the root logger has none. The default format shows severity, logger name, and message.

Configure a named logger

Save as demo_logging_2.py:

import logging
import sys

logging.basicConfig(
    level=logging.INFO,
    format="%(levelname)s %(name)s: %(message)s",
    stream=sys.stdout,
)
logger = logging.getLogger("inventory")

remaining_notebooks = 2
logger.debug("Reading stock records")
logger.info("Checked %s products", 3)
logger.warning("Only %s notebooks remain", remaining_notebooks)

logger.setLevel(logging.ERROR)
logger.warning("This warning is below the new threshold")
logger.error("Cannot save inventory")

Run:

python3 demo_logging_2.py

Output on standard output:

INFO inventory: Checked 3 products
WARNING inventory: Only 2 notebooks remain
ERROR inventory: Cannot save inventory

The named logger initially inherits the root threshold. setLevel() then changes its own threshold. Passing values separately with %s lets logging defer message formatting until needed; argument expressions themselves still run when the call is made.

stream=sys.stdout is an explicit choice here. Without it, the default console handler writes to standard error. Keep logs on standard error when standard output carries machine-readable results.

Choose useful levels

  • DEBUG: details for diagnosing a problem
  • INFO: ordinary progress
  • WARNING: an unexpected condition that still allows progress
  • ERROR: an operation failed
  • CRITICAL: a failure that threatens the whole program

Configure logging once, near the application’s entry point. basicConfig() normally does nothing if the root logger already has handlers, including in notebooks. These fresh processes avoid that issue.

In reusable modules, logging.getLogger(__name__) gives each module a recognizable name. Keep passwords, access tokens, and private records out of log messages.

References

Acknowledgements

This post was created with assistance from AI.

Last updated on