Leave a useful trail.
Record what happened without scattering print statements through application code.
01 The idea
Logging separates diagnostic events from a program’s user-facing output. A logger names the source of an event; levels indicate severity; handlers decide where records go. Configure logging in the application entry point and let reusable modules obtain their own named loggers. Useful logs explain context without disclosing credentials or personal data.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
import logging, sys
logging.basicConfig(level=logging.INFO, stream=sys.stdout, format="%(levelname)s %(message)s", force=True)
logger = logging.getLogger("lab.import")
logger.debug("Detailed row trace")
logger.info("Imported %d rows", 3)
logger.warning("Skipped %d invalid row", 1)INFO Imported 3 rows WARNING Skipped 1 invalid row
03 Under the hood
- 1
INFO is the configured threshold, so the DEBUG record is not emitted. A level is a filtering signal, not a substitute for deciding what should be recorded.
- 2
Passing arguments separately lets logging defer message formatting until needed. It does not sanitise the values automatically.
- 3
logger.exception inside an except block includes a traceback. Log an error at the boundary that handles it; repeatedly logging and re-raising at every layer creates duplicate noise.
04 Your turn, builder
Configure a logger to emit only warnings and errors, then demonstrate that an INFO message is hidden.
Reveal one possible solution +
import logging, sys
logging.basicConfig(level=logging.WARNING, stream=sys.stdout, format="%(levelname)s %(message)s", force=True)
log = logging.getLogger("lab")
log.info("hidden")
log.error("Something needs attention")05 Check your signal
What does a logger’s level help control?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.