Logging in Python

From the Python cheat sheet ยท Standard Library ยท verified Jul 2026

Logging

Structured logging instead of print() for real applications.

python
import logging

# Basic setup โ€” call once at app start
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)

log = logging.getLogger(__name__)

log.debug("Detailed diagnostic info")
log.info("Normal event happened")
log.warning("Something looks off")
log.error("Something failed")
log.exception("Failed with traceback")  # Inside an except block
๐Ÿ’ก Use logging in real apps; print() is for one-off scripts
โšก Pass args (log.info("hi %s", name)) instead of formatting upfront โ€” it is lazy
๐Ÿ“Œ log.exception() inside except blocks auto-includes the traceback
๐ŸŸข Use logging.getLogger(__name__) per module so you can tune levels per package

More Python tasks

Back to the full Python cheat sheet