Logging & Debugging
Learn professional logging and debugging techniques. Master the logging module and pdb debugger.
Learn professional logging and debugging techniques. Master the logging module and pdb debugger. This hands-on tutorial focuses on practical implementation of logging & debugging concepts.
Logging & Debugging
Professional applications use logging instead of print statements. Learn to track application behavior and debug effectively.
The logging Module
The logging module is a powerful standard library that tracks events in your software.
Why not just use print?
- Levels: You can categorize messages (Error vs. Info).
- Destinations: Send logs to files, emails, or external services.
- Formatting: Automatically add timestamps and line numbers.
Basic Configuration
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(message)s'
)
Log Levels
Setting the Level
Setting a level ignores all messages below that level.
logger.setLevel(logging.WARNING)
# Now DEBUG and INFO messages are ignored
| Level | Value | When to Use |
|---|---|---|
| DEBUG | 10 | Detailed information for diagnosing problems |
| INFO | 20 | General informational messages |
| WARNING | 30 | Warning messages (potential issues) |
| ERROR | 40 | Error messages (serious problems) |
| CRITICAL | 50 | Critical errors (program may crash) |
Logging to File
Logging to File
In production, you want logs saved to a file for later analysis. You use FileHandler for this.
Example
import logging
logging.basicConfig(
filename='app.log', # Log to this file
level=logging.INFO
)
logging.info("This is saved to the file")
Application Logger Example
Application Logger Example
When building larger applications, avoid using the root logger (logging.<method>). Instead, create a named logger for each module.
logger = logging.getLogger(__name__)
AI Mentor
Confused about "Python logging debugging log levels"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3Which log level is most severe?
Key Takeaways
✅ Logging is better than print for production code.
✅ Log levels control verbosity (DEBUG to CRITICAL).
✅ Formatters customize log message appearance.
✅ Handlers control where logs go (console, file, etc.).
Keep coding! 🚀