Python Logging – Track Info, Warnings & Errors Efficiently
Introduction – Why Use Logging in Python?
Debugging with print() is fine—for toy scripts.
But in real-world applications, you need a robust and scalable way to:
- Track what happened (and when)
- Record errors and warnings
- Write logs to files or external systems
- Debug without cluttering production output
That’s where Python’s built-in logging module comes in.
In this guide, you’ll learn:
- How Python logging works
- Logging levels and use cases
- How to log to a file
- Formatting and configuring logs
- Real-world practices for robust logging
Getting Started with Python Logging
import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message.")
Output:
INFO:root:This is an info message.
basicConfig() sets up the logging system and configures the default behavior.
Logging Levels Explained
Python logging uses levels to classify the importance of events:
| Level | Method | Use For |
|---|---|---|
| DEBUG | logging.debug() | Detailed information for debugging |
| INFO | logging.info() | Confirmation that things work as expected |
| WARNING | logging.warning() | Something unexpected, non-breaking |
| ERROR | logging.error() | A serious problem, but still running |
| CRITICAL | logging.critical() | Fatal error, app may crash |
Example – Logging at Multiple Levels
logging.debug("Debugging message")
logging.info("Info message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical error")
By default, only WARNING and above are shown unless you set a lower level.
Logging to a File
logging.basicConfig(
filename="app.log",
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.info("File logging initialized.")
Creates app.log file with:
2025-05-14 21:00:00,123 - INFO - File logging initialized.
Great for persistent error tracking, especially in production.
Logging Formatter and Custom Configuration
Format Tokens:
| Token | Description |
|---|---|
%(asctime)s | Timestamp |
%(levelname)s | Log level |
%(message)s | Log message |
%(name)s | Logger name |
%(lineno)d | Line number |
%(funcName)s | Function name |
Advanced Configuration with logging.config
import logging.config
logging.config.dictConfig({
'version': 1,
'formatters': {
'detailed': {
'format': '%(asctime)s %(name)s [%(levelname)s]: %(message)s'
}
},
'handlers': {
'file': {
'class': 'logging.FileHandler',
'filename': 'advanced.log',
'formatter': 'detailed'
}
},
'root': {
'handlers': ['file'],
'level': 'INFO'
}
})
logging.info("Configured with dictConfig.")
Real-World Use Case – Error Logging in try/except
try:
x = 1 / 0
except ZeroDivisionError as e:
logging.error("Exception occurred", exc_info=True)
Output with traceback:
ERROR:root:Exception occurred
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
Use exc_info=True to include full stack trace.
Best Practices for Logging
| Do This | Avoid This |
|---|---|
Use appropriate levels (info, error) | Logging everything as print() |
| Use log files for long-term tracking | Overwriting the same log file |
Include traceback using exc_info=True | Hiding errors with vague messages |
Use RotatingFileHandler for big files | Letting logs grow indefinitely |
Summary – Recap & Next Steps
Python’s logging module provides a powerful, scalable way to track events, debug issues, and keep your programs stable in production.
Key Takeaways:
- Use
logging.debug(),info(),warning(),error(), andcritical()as needed - Configure logging with
basicConfig()ordictConfig() - Use log files and rotation for persistent tracking
- Always log exceptions using
exc_info=True
Real-World Relevance:
Used in web apps, data pipelines, automation scripts, and enterprise software to monitor health and troubleshoot effectively.
FAQ – Python Logging
What’s the default logging level?
WARNING. Only messages of warning, error, and critical are shown by default.
How do I log to both console and file?
Use multiple handlers:
handler1 = logging.StreamHandler()
handler2 = logging.FileHandler("app.log")
Then add both to the logger.
Can I rotate logs automatically?
Yes. Use RotatingFileHandler or TimedRotatingFileHandler from logging.handlers.
Is logging better than print for debugging?
Absolutely. Logging provides levels, formats, file output, and error tracebacks.
Can I suppress logs in production?
Yes. Set a higher logging level like WARNING or ERROR using basicConfig(level=logging.ERROR).
Share Now :
