Error Handling and Debugging
26 min read
Logging
Logging
Sometimes print() is not enough.
Real programs need a better way to record what happened.
Python gives us the logging module.
What Is Logging?
Logging means saving messages about your program.
These messages can show:
- normal actions
- warnings
- errors
- debugging information
Why Logging Matters
Logging helps you:
- understand what happened
- find bugs later
- track errors
- monitor programs
Import logging
import logging
Basic Logging Setup
Use basicConfig().
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Program started")
Output Example
INFO:root:Program started
Common Log Levels
DEBUG= detailed infoINFO= normal eventsWARNING= something unusualERROR= problem happenedCRITICAL= serious problem
Example: Different Levels
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("Loading data")
logging.info("User logged in")
logging.warning("Low disk space")
logging.error("File missing")
logging.critical("System stopped")
Example Output
DEBUG:root:Loading data
INFO:root:User logged in
WARNING:root:Low disk space
ERROR:root:File missing
CRITICAL:root:System stopped
Logging to a File
Save logs into a file.
import logging
logging.basicConfig(
filename="app.log",
level=logging.INFO
)
logging.info("App opened")
Now the message is saved in app.log.
Logging Errors with try
import logging
logging.basicConfig(level=logging.ERROR)
try:
print(10 / 0)
except ZeroDivisionError:
logging.error("Cannot divide by zero")
Output Example
ERROR:root:Cannot divide by zero
Why Not Only print()?
print() is useful while learning.
Logging is better for real apps because it can:
- show levels
- save to files
- keep history
- organize messages
Code Along
Create a program that logs:
- Program started
- User clicked button
- Program ended
Mini Challenge
Build a safe logger.
Steps:
- Ask for a number
- If valid, log:
INFO: Number accepted
- If invalid, log:
ERROR: Invalid number
Real World Use Case
Apps use logging for websites, servers, finance tools, mobile apps, and debugging systems.
Quiz
- What is logging?
- Name two log levels.
- Why is logging better than
print()in real apps? - Can logs be saved to a file?
Assignment
Create a program that logs three messages: one info, one warning, and one error.
Summary
You learned how to use Python logging to record events, warnings, and errors for debugging and monitoring.