When to Use Logging
Quick Start
Logging Levels
Levels in order of severity:Logging to Files
Basic File Logging
File Modes
Format Strings
Common Format Attributes
%(name)s- Logger name%(levelname)s- Logging level%(message)s- Log message%(asctime)s- Timestamp%(filename)s- Source filename%(lineno)d- Line number%(funcName)s- Function name%(process)d- Process ID%(thread)d- Thread ID
Custom Formatting
Variable Data
Using Format Strings
Advanced Configuration
Exception Logging
Log Exceptions with Traceback
Log Without Traceback
Logger Hierarchy
Parent-Child Relationships
Best Practice: Module-Level Loggers
Configuration Files
INI Format
Dictionary Configuration
Library Logging
For Library Authors
Library Best Practices:
- Use
logging.getLogger(__name__)in each module - Add
NullHandler()to prevent warnings - Never configure handlers in library code
- Document what loggers your library uses
Common Patterns
Conditional Expensive Operations
Context Information
Web Request Logging
Troubleshooting
Debug Logging Setup
Summary
Key takeaways:- Use
logger = logging.getLogger(__name__)in each module - Configure logging once at application entry point
- Use appropriate log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL)
- Never add handlers in library code
- Use
logger.exception()in except blocks - Format messages with placeholders, not string concatenation
