What You Will Learn
Intermediate
- The logging module and log levels
- Logging to file and console
- Format and handlers
Terminalpython
import logging
# Basic setup
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s",
filename="app.log"
)
# Log levels (lowest to highest)
logging.debug("Debug info - detailed troubleshooting")
logging.info("Info - normal operation")
logging.warning("Warning - something unexpected")
logging.error("Error - something failed")
logging.critical("Critical - system cannot continue")Log Levels
| Level | When to use | Numeric |
|---|---|---|
| DEBUG | Detailed diagnostic info | 10 |
| INFO | Confirm things work | 20 |
| WARNING | Something unexpected, still working | 30 |
| ERROR | Something failed | 40 |
| CRITICAL | System cannot continue | 50 |
Use logging, not print
print() is for development. logging is for production: timestamps, levels, file output, and you can control verbosity without changing code.Practical Exercise
import logging and configure with basicConfig
Log at each level: debug, info, warning, error
Log to a file: filename='app.log'
Change level to WARNING - see debug/info disappear
Add format: '%(asctime)s - %(levelname)s - %(message)s'
Key Takeaways
- logging is better than print: levels, files, formatting.
- 5 levels: DEBUG < INFO < WARNING < ERROR < CRITICAL.
- basicConfig: set level, format, filename.
- Set level=logging.WARNING to hide debug/info.
- Use logging.exception() inside except blocks - includes traceback.
Comments
Comments
Post a Comment