Skip to content

Beginning of the lesson

Logging in Python

A structured, leveled way for real programs to report what they are doing

Big idea: The logging module lets your program emit a stream of timestamped, categorised messages. Unlike print(), each message carries a severity level, can be routed to several destinations at once (console, file, network), and can be turned up or down without editing your code. Logging is how intermediate-scale and production programs tell you what happened, when, and how bad it was.
By the end you will be able to:
  • explain why print() stops scaling as a debugging tool,
  • choose the right one of the five log levels,
  • get a named logger and understand the root logger,
  • attach handlers and formatters to send logs to the console and to a file,
  • record exceptions with a full traceback using logger.exception.

1. Why print() is not enough

When you were learning the language, print() was the natural way to peek at what your code was doing. It works, but it has no notion of importance and no built-in structure. Every message is equal, they all go to standard output, and to silence them you have to physically delete or comment out lines.

A real program needs to answer questions like: What routine information happened? What warnings did we survive? What errors actually broke something? With print() you cannot tell these apart, and you certainly cannot say "show me warnings and worse in production, but everything while I debug" without rewriting code.

Concernprint()logging
Severity of a messagenone, all equalfive levels
Where output goesalways stdoutany handlers you attach
Turn messages offedit the codechange one level setting
Timestamp and sourceyou add it by handthe formatter adds it
Show a full tracebackmanualexc_info / exception()

Logging keeps the convenience of "print a message" while adding the control a growing program needs.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers