Skip to main content
Albero Academy

Logging

Record what your program does with the logging module instead of print.

Exceptions9 min

For anything beyond a throwaway script, logging beats print. It records severity levels and timestamps, can be filtered, and can be routed to files or external systems — all configured in one place, without editing the code that emits the messages.

Levels & basic setup

logging
import logging
logging.basicConfig(
level=logging.INFO, # minimum level to show
format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger(__name__)
log.debug("verbose detail") # hidden (below INFO)
log.info("Started processing")
log.warning("Missing optional config")
log.error("Failed to connect")
LevelUse for
DEBUGDetailed diagnostic info
INFONormal events ("started", "processed 100")
WARNINGSomething unexpected but handled
ERRORA failure in an operation
CRITICALThe program may not continue

Why not print?

Key takeaways

  1. 01Use logging, not print, for anything beyond quick scripts.
  2. 02Levels DEBUG < INFO < WARNING < ERROR < CRITICAL filter by severity.
  3. 03basicConfig sets the level, format and destination once.
  4. 04Change the level to control verbosity without editing log calls.
  5. 05log.exception() inside except records the message plus the traceback.

Finished this chapter?

Mark it complete to track your progress through Python.