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
loggingModule: 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, openapp.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
- DEBUG: Detailed info for diagnosing problems.
- INFO: Confirmation that things are working as expected.
- WARNING: Something unexpected happened, but the app is still working.
- ERROR: A serious problem; the app couldn't perform a function.
- 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
- Create a script that simulates a system monitor.
- Log an INFO message when the script starts.
- Create a loop that "checks" a value (e.g., CPU temperature).
- If the value is above 70, log a WARNING.
- If it's above 90, log a CRITICAL message and stop the loop.
- Open your
app.logfile to see the results.
Quick Knowledge Check
- What is the benefit of logging over printing?
- Name the five levels of logging in order of severity.
- What is the purpose of
%(asctime)sin a log format? - 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
loggingmodule 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!