Python Logging Tutorial: Stop Using Print() for Debugging
Every beginner Python developer uses `print("here")` to find bugs. Every senior developer uses `logging`. Why? Because `print` is temporary, but logs are forever.
Imagine you have a script running on a server at 3:00 AM. It crashes. If you used print(), that error message is gone forever, lost in the console void. If you used logging, that error is saved to a file with a timestamp, the module name, and the severity level.
The logging module is built into Python. It requires zero installation. It allows you to switch on/off messages without deleting code, and it lets you write to files and consoles simultaneously.
Step 1: The Basic Setup
To start using logging, you need to import it and configure it once at the start of your script.
Step 2: Understanding Levels
The magic of logging is the Level system. You categorize messages by importance. When you run your code, you set a "Threshold." Only messages at or above that threshold get shown.
- DEBUG (10): Detailed info for diagnosing problems (e.g., "Variable x is 5").
- INFO (20): Confirmation that things are working (e.g., "Connected to database").
- WARNING (30): Something unexpected happened, but code is still running (e.g., "Disk space low").
- ERROR (40): A function failed (e.g., "File not found").
- CRITICAL (50): The application crashed (e.g., "Out of Memory").
DEBUG to see everything. When you deploy, change level to WARNING. All your debug and info messages disappear automatically. No code deletion required.
Step 3: Writing to a File
This is the killer feature. You can save your logs to a file so you can read them later.
Now, every time your script runs, it appends the history to `app.log`. You have a permanent record of what your code did.
Logging vs. Print: A Comparison
| Feature | Print() | Logging |
|---|---|---|
| Destination | Console only | Console, File, Email, Server |
| Timestamps | Manual | Automatic |
| Categorization | None | Levels (Debug, Error, etc.) |
| Production Ready | No | Yes |
Conclusion
Transitioning from `print` to `logging` is a rite of passage for Python developers. It separates the hobbyists from the professionals. It gives you control, history, and peace of mind.
Stop printing. Start logging.

Comments
Post a Comment