Module 5 Lesson 10: Logging and Debugging Files
·Programming

Module 5 Lesson 10: Logging and Debugging Files

Keep a paper trail. Learn how to use Python's logging module to record errors and system events into files, making debugging much easier.

Module 5 Lesson 10: Logging and Debugging Files

Using print() for debugging is fine when you're a beginner, but professional apps don't print errors to the screen for users to see. Instead, they write them to a hidden Log File. This allows developers to see exactly what happened days or weeks after an error occurred.

Lesson Overview

In this lesson, we will cover:

  • The logging Module: Python's built-in record keeper.
  • Log Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.
  • Logging to a File: Creating your own app.log.
  • Formatting Logs: Adding timestamps and line numbers automatically.

1. Why Logging?

Imagine your program crashes at 3:00 AM while you're asleep.

  • With print: The error is gone when the program closes. You have no idea what happened.
  • With logging: You wake up, open app.log, and see: [03:00:15] ERROR: Database connection lost in database.py line 45.

2. Setting Up a Basic Logger

To start logging to a file, we use logging.basicConfig().

import logging

# Configure logging to save to 'app.log'
logging.basicConfig(
    filename='app.log', 
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

logging.info("Program started.")
logging.warning("User attempted a low-security action.")
logging.error("Failed to connect to the server.")

3. The 5 Levels of Logging

  1. DEBUG: Detailed info for diagnosing problems.
  2. INFO: Confirmation that things are working as expected.
  3. WARNING: Something unexpected happened, but the app is still working.
  4. ERROR: A serious problem; the app couldn't perform a function.
  5. CRITICAL: A fatal error; the program may be unable to continue.

4. Practical Example: Logging Exceptions

You can use the logging module inside your except blocks to record when crashes happen.

try:
    result = 10 / 0
except ZeroDivisionError:
    logging.error("A user tried to divide by zero!")

Practice Exercise: The System Monitor

  1. Create a script that simulates a system monitor.
  2. Log an INFO message when the script starts.
  3. Create a loop that "checks" a value (e.g., CPU temperature).
  4. If the value is above 70, log a WARNING.
  5. If it's above 90, log a CRITICAL message and stop the loop.
  6. Open your app.log file to see the results.

Quick Knowledge Check

  1. What is the benefit of logging over printing?
  2. Name the five levels of logging in order of severity.
  3. What is the purpose of %(asctime)s in a log format?
  4. By default, which log level is the minimum (i.e., lower levels won't be shown)?

Key Takeaways

  • Logging provides a persistent history of what your program did.
  • The logging module is built-in and very powerful.
  • Use different levels (INFO, ERROR, etc.) to categorize your messages.
  • Logging to a file is essential for professional software development.

What’s Next?

We’ve finished the lessons for Module 5! It’s time to put your file-handling and error-catching skills together in our Hands-on Projects where we'll build a Secure Data Archive!

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn