π 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 :