Introduction
Logging provides a way to track events during program execution, better than print statements.
Basic Logging
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.debug("Debug message")
logger.info("Info message")
logger.warning("Warning message")
logger.error("Error message")
Configuration
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
handlers=[
logging.FileHandler("app.log"),
logging.StreamHandler()
]
)
Log Levels
| Level | Numeric | Use Case |
|---|---|---|
| DEBUG | 10 | Detailed debugging info |
| INFO | 20 | General events |
| WARNING | 30 | Potential issues |
| ERROR | 40 | Errors occurred |
| CRITICAL | 50 | Serious errors |
Practice Problems
- Set up logging with file output
- Create logger per module
- Use different log levels
- Configure log formatting
- Rotate log files