Logging Mechanisms in Python
Basic Logging Configuration
import logging
## Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename='app.log'
)
def error_prone_function():
try:
## Some risky operation
result = 10 / 0
except ZeroDivisionError:
logging.error("Division by zero occurred")
graph TD
A[Error Tracking Tools] --> B[Built-in Tools]
A --> C[Third-Party Solutions]
B --> D[logging module]
B --> E[traceback module]
C --> F[Sentry]
C --> G[Rollbar]
C --> H[New Relic]
Tool |
Type |
Key Features |
Complexity |
logging |
Built-in |
Simple, flexible |
Low |
traceback |
Built-in |
Detailed error information |
Low |
Sentry |
Third-party |
Real-time error monitoring |
Medium |
Rollbar |
Third-party |
Comprehensive error tracking |
Medium |
Advanced Logging Techniques
import logging
from logging.handlers import RotatingFileHandler
## Create a rotating file handler
handler = RotatingFileHandler(
'app.log',
maxBytes=10000,
backupCount=3
)
logger = logging.getLogger('advanced_logger')
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
def complex_operation():
try:
## Simulated complex operation
raise ValueError("Custom error")
except ValueError as e:
logger.exception("An error occurred during operation")
Error Tracking with Decorators
def error_tracker(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
logging.error(f"Error in {func.__name__}: {str(e)}")
## LabEx Tip: Use decorators for consistent error tracking
raise
return wrapper
@error_tracker
def risky_function(x, y):
return x / y
Monitoring and Alerting
Custom Error Monitoring
import sys
import traceback
def global_error_handler(exc_type, exc_value, exc_traceback):
"""Global error handling mechanism"""
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
## Log detailed error information
logging.error(
"Uncaught exception",
exc_info=(exc_type, exc_value, exc_traceback)
)
## Set global exception handler
sys.excepthook = global_error_handler
Best Practices for Error Tracking
- Use appropriate logging levels
- Implement comprehensive error capture
- Configure log rotation
- Use context-rich error messages
- Integrate with monitoring systems
- Minimize logging in performance-critical sections
- Use appropriate logging levels
- Configure log rotation to manage file sizes
- Consider asynchronous logging for high-performance applications
By leveraging these error tracking tools and techniques, developers can create more reliable and maintainable Python applications with comprehensive error monitoring and management.