Python · Intermediate level

Intermediate level · Module 2: Error Handling and Defensive Programming · Lesson 3 of 3

Logging Program Activity

Replace scattered print statements with the logging module so problems can be investigated later.

In this lesson you will

  • Configure logging to a file with levels
  • Choose suitable log levels

Key concepts

logging levelslog filebasicConfigaudit trail

The lesson

print() is fine while developing, but a program that runs unattended needs a record of what happened. The logging module writes timestamped messages at levels — DEBUG, INFO, WARNING, ERROR — to the screen, a file or both.

Configure logging once at the start with logging.basicConfig(filename='cleaner.log', level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s'). Then call logging.warning(...) whenever a row is rejected.

Never log passwords, full ID numbers or other sensitive personal data. Log enough to find the problem — a row number and reason — without exposing people's information.

Step by step

  1. Configure logging with a file name, level and format.
  2. Replace print statements for rejected rows with logging.warning.
  3. Log an INFO summary at the end of the run.
  4. Open the log file and check each entry has a timestamp and reason.

Practice activity

Add logging to your CSV script so every rejected row is written to a log file at WARNING level with its reason.

Expected result: A log file listing each rejected row with a timestamp and reason.

Check your understanding

  1. Which log level suits 'row 14 rejected: invalid phone number'?

    Show answer

    WARNING: the program continues, but something needs attention.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.