Python Files & Errors
Python Logging
The logging module is Python's built-in, professional way to record what your program is doing — far more powerful and configurable than sprinkling print() statements everywhere.
Why Not Just Use print()?
print() is fine for quick experiments, but it has no concept of severity, no timestamps, and no easy way to turn messages on or off in production. The logging module solves all of this: it tags every message with a level, a timestamp, and lets you send output to a file, the console, or both, without changing your code.
A First Logging Example
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Application started")
logging.warning("Disk space running low")
logging.error("Failed to connect to database")INFO:root:Application started
WARNING:root:Disk space running low
ERROR:root:Failed to connect to databaseLogging Levels
Every log message has a severity level. basicConfig(level=...) sets the minimum level that actually gets shown — anything below it is silently ignored, so you can turn verbosity up or down without touching your logging calls.
| Level | Number | Use For |
|---|---|---|
| DEBUG | 10 | Detailed info useful only while developing |
| INFO | 20 | Confirmation that things are working as expected |
| WARNING | 30 | Something unexpected, but the program still works |
| ERROR | 40 | A serious problem — some function could not run |
| CRITICAL | 50 | A very serious error — the program may be unable to continue |
Set level=logging.DEBUG while developing to see everything, then switch to level=logging.WARNING in production so only real problems show up.
Logging to a File with a Handler
A handler decides where log messages actually go — the console, a file, or even a remote server. basicConfig can attach a filename directly for simple cases.
import logging
logging.basicConfig(
filename="app.log",
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.info("User signed up")
logging.error("Payment failed for order 1024")- Import logging and call logging.basicConfig(level=...) once, near the start of your program.
- Use logging.debug/info/warning/error/critical() instead of print() for real applications.
- Only messages at or above the configured level are shown or saved.
- format lets you add timestamps and level names automatically to every message.
For larger projects, create a named logger with logging.getLogger(__name__) instead of using the root logger directly — it makes it easy to tell which module a message came from.
