← All lessons

Logging

Sign in · Sign up

Lesson 8.6

print shows an event on screen and forgets it. logging records events in a file, so you can work out later what happened:

import logging

logging.basicConfig(
    filename="app.log",
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
)

logging.info("The program started")

The file app.log gets a line:

2025-01-01 12:00:00,000 INFO The program started

Let's go through the setup: filename picks the file, level=logging.INFO allows records of the info level and above (by default only warning and above are written), and format sets the shape of the line.

The check gives the values code and raw — the error code and what the user typed. Write:

  1. close the log handlers from previous runs (logging.getLogger().handlers) and wipe app.log with logbook.reset;
  2. set up logging for this file at the logging.INFO level;
  3. if raw is a number, number gets it, and an info record with the text Number: <number> goes to the log;
  4. if raw is not a number, number stays None, and an error record with the text Bad input: <code> goes to the log;
  5. read app.log with logbook.read and print the lines without the date — the module has logbook.without_time for that.

logbook is a small module next to the program: reset clears the file, read returns its lines, without_time removes the date and time from a line.

Hint

Three actions: clear the log, write to it, read it back.

First close the old handlers and wipe the file with logbook.reset. basicConfig sets the file, the level and the format. In except — logging.error, in else — logging.info, then logbook.read and without_time.