Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.9 — Logging Instead of print
Python · Example 4 of 6

Two handlers with different levels, and lazy formatting

Everything goes to the file; only warnings go to the screen. The __str__ method shows that the text is built only when needed.

The logging module records what your program is doing with a severity level, a source name and a format, and can send the records anywhere. It replaces scattered print calls with output you can filter, store and search.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 7 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Call logging.basicConfig so that INFO and above appear in the form LEVEL: message (the format string is "%(levelname)s: %(message)s"). Then log one info line and one error line from a logger called pipeline.

02

Write safe_divide(a, b) that returns a / b. When b is zero it must call logger.exception(...) with a short message and return None. Call it with (6, 3) and with (1, 0).

03

Make a logger jobs that writes DEBUG and above to a file jobs.log (use a FileHandler and setLevel(logging.DEBUG) on the logger). Log three messages, then read the file and print how many lines it has (it should print 3).

Explain it without notes

01

Name the five standard log levels in order and explain the default threshold.

02

Why use logging.getLogger(__name__) in every module rather than the root logger?

03

Why should you write logger.info("x=%s", x) instead of an f-string?

04

How do you record a caught exception with its traceback?

Two handlers with different levels, and lazy formatting
Sign in to run this example in your browser.

Expected output

(building the text)
screen> queue is long
['DEBUG details: costly value', 'INFO job started', 'WARNING queue is long']