Python Basics: Recording Events with logging
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.pyOutput on standard error:
WARNING:root:Only two notebooks remainThe 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.pyOutput on standard output:
INFO inventory: Checked 3 products
WARNING inventory: Only 2 notebooks remain
ERROR inventory: Cannot save inventoryThe 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 problemINFO: ordinary progressWARNING: an unexpected condition that still allows progressERROR: an operation failedCRITICAL: 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.