Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Python as a system
EXPERIMENT 41 / 101

Leave a useful trail.

Record what happened without scattering print statements through application code.

ADVANCED LAB
BY NAVAN SAMI◷ 9 MIN READPYTHON 3

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.

logging.py
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)
↳ EXPECTED OUTPUT
INFO Imported 3 rows
WARNING Skipped 1 invalid row

03 Under the hood

  1. 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. 2

    Passing arguments separately lets logging defer message formatting until needed. It does not sanitise the values automatically.

  3. 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

A SMALL MISSION

Configure a logger to emit only warnings and errors, then demonstrate that an INFO message is hidden.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

What does a logger’s level help control?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.