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
import logginglogging.basicConfig(level=logging.INFO, # minimum level to showformat="%(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")
| Level | Use for |
|---|---|
DEBUG | Detailed diagnostic info |
INFO | Normal events ("started", "processed 100") |
WARNING | Something unexpected but handled |
ERROR | A failure in an operation |
CRITICAL | The program may not continue |
Why not print?
Key takeaways
- 01Use logging, not print, for anything beyond quick scripts.
- 02Levels DEBUG < INFO < WARNING < ERROR < CRITICAL filter by severity.
- 03basicConfig sets the level, format and destination once.
- 04Change the level to control verbosity without editing log calls.
- 05log.exception() inside except records the message plus the traceback.
