LESSON · 1 OF 5

Logging versus print

Logging versus print

A quick print is fine while you're poking at a script. Once that script runs unattended, on a schedule or as part of a pipeline, print stops being enough. The logging module in the standard library is built for programs that run on their own and need a record of what they did.

What print can't do

A print call always fires, always goes to the same place, and carries no context. When a scheduled job fails at 3am, a screen full of bare print lines tells you little. You can't dial the detail up or down, you can't tell an ordinary message from an emergency, and you can't send the output to a file without redirecting the whole program.

What logging adds

Logging gives you three things print never will:

  • Severity. Every message has a level, from routine detail up to critical failure, so you can tell what matters at a glance.
  • A volume knob. You set a threshold, and messages below it are dropped. Turn up detail while debugging, turn it down in production, without touching the log calls themselves.
  • Destinations and format. The same messages can go to the screen, a file, or both, each line stamped with a time and a level.

The first log message

The simplest use looks a lot like print:

python
import logging

logging.warning("disk space is low")

Out of the box this prints WARNING:root:disk space is low. The level is right there in the output, which a plain print could never give you. The next nodes cover the levels and how to control where these lines go and what they look like.

What this node introduces

  • logging is the standard tool for output from scripts that run unattended.
  • It adds severity levels, a threshold to filter by, and control over format and destination.
  • logging.warning(...) and its siblings replace print for this.
Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute