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