What is Python Logging?
In development, we use
print() to see what's happening. But in real-world applications, you need something more robust. The logging module allows you to track events, errors, and system status in a standard way, often directing output to files or remote services.python
Log Levels: When to Use Each
| Level | Value | Used For... |
|---|---|---|
| DEBUG | 10 | Detailed info, usually only for developers. |
| INFO | 20 | Normal system events (startup, user login). |
| WARNING | 30 | Something unexpected happened, but system still works. |
| ERROR | 40 | Serious problem; some functionality failed. |
| CRITICAL | 50 | Fatal error; the program cannot continue. |
Configuring the Logger: basicConfig
You can easily configure logging to write to a file with customized formatting.
python
Advanced Logging: Components
For larger projects, you should use the component-based approach with
Loggers, Handlers, and Formatters.- Loggers: The application interface for logging.
- Handlers: Determine where logs go (Console, File, Email, etc.).
- Formatters: Define the text format of your logs.
python
Capturing Exception Details
Logging is especially useful for recording the full "stack trace" of an error when an exception occurs. Use
exc_info=True.python
Why Not Use print()?
- Metadata: Logging includes timestamps, log level, and the file/line where the event occurred.
- Granularity: You can easily turn off
DEBUGmessages when your app goes into production. - Multiple Outputs: Send logs to a file, database, and your terminal simultaneously!
- Standardization: Every Python third-party library uses the
loggingmodule, meaning you can capture logs from your dependencies too.
Summary
| Term | Description |
|---|---|
| basicConfig | Simple setup for logging to console/file |
| Log Levels | DEBUG, INFO, WARNING, ERROR, CRITICAL |
| Logger | The main interface to record logic |
| Handler | Directs logs to specific locations |
| Formatter | Controls the layout of the log text |
| exc_info | Include stack trace (traceback) in logs |
| Best For | Error tracking, audits, system monitoring |
| Rotation | Use RotatingFileHandler to prevent logs from getting too large |