Learn Python
>>> exception_handling.logging

Logging in Python

#concept

The logging module is Python's built-in, standard way to record what a program is doing while it runs — far more capable than scattering print() statements throughout code, since logging supports severity levels, timestamps, and configurable destinations like a file, without needing to touch the code that generates each message.

#how it works
1

import logging

Brings in the module, ready to use with sensible defaults.

2

Each call has a severity level

debug(), info(), warning(), error(), and critical(), from least to most severe.

3

Only warning() and above show by default

debug() and info() stay suppressed unless the level is configured lower.

4

basicConfig() controls what’s shown

Sets the minimum level, and can redirect output to a file instead of the console.

5

Logging can be toggled without touching the code

Unlike print(), messages can be turned on, off, or redirected purely through configuration.

#example
import logging
 
logging.basicConfig(level=logging.INFO)
 
logging.debug("This won't show by default")
logging.info("Starting process")
logging.warning("Disk space is low")
logging.error("Failed to save file")
Output
INFO:root:Starting process
WARNING:root:Disk space is low
ERROR:root:Failed to save file
1logging.basicConfig(level=logging.INFO) sets the minimum severity shown to INFO, one step below the default (WARNING).
2debug() is still below even that lowered threshold, so it stays silent.
3info(), warning(), and error() all meet or exceed the configured level, so each prints, prefixed with its severity and the default logger name, root.
#use cases
Recording what a running program is doing, especially useful for diagnosing problems in production, long after the fact
Distinguishing routine information from genuine warnings and errors, using different severity levels
Turning verbose debug output on temporarily while troubleshooting, without adding or removing print() statements
Sending log output to a file for later review, instead of only the console, without changing any logging calls in the code

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.