Debugging and Logging
Master debugging and diagnostic logging in Python. Read tracebacks, inspect variables with breakpoint(), and record production telemetry with the logging module.
When code fails or behaves unpredictably, almost every beginner starts by littering their file with random print statements:
# The chaotic print debugging habit:
print("HERE 1")
print("x is:", x)
print("INSIDE LOOP")
print("HERE 2 - IF YOU SEE THIS IT BROKE")
While print() statements can give quick clues for trivial scripts, relying solely on print debugging becomes overwhelming in larger programs:
- You have to manually find and delete every print statement before shipping to production.
- Print statements offer no timestamps, severity levels, or file locations.
- Print statements cannot pause execution to let you inspect variables live.
Professional Python engineers solve bugs using two dedicated tools:
- Interactive Debuggers (
breakpoint(), pdb): Freezes time, letting you step line by line and test values live. - The
loggingModule: Records timestamped, categorized diagnostic telemetry in development and production environments.
1. How to Read a Python Traceback
When an unhandled error crashes a Python script, it prints a Traceback. Beginners often find this wall of red text intimidating, but a traceback is actually a detailed roadmap describing exactly where the problem occurred:
Traceback (most recent call last):
File "checkout.py", line 42, in <module>
process_order(cart)
File "checkout.py", line 18, in process_order
total = calculate_subtotal(cart["items"])
File "checkout.py", line 8, in calculate_subtotal
return sum(item["price"] for item in items)
KeyError: 'price'
The Golden Rule of Tracebacks:
Always look at the VERY LAST LINE first!
- The Last Line:
KeyError: 'price'tells you the exact exception and message. One of the dictionary items in the list does not have a'price'key! - The Line Above It: Shows the exact line of code that triggered the failure (
return sum(...)). - The Call Stack: Traces upward, showing how line 42 called line 18, which called line 8.
2. Interactive Debugging with breakpoint()
In Python 3.7+, Python introduced the built-in breakpoint() function. Placing this function anywhere in your code causes Python to pause execution and open an interactive Pdb (Python Debugger) terminal shell:
def calculate_grade(scores):
total = sum(scores)
count = len(scores)
# Freeze time right here!
breakpoint()
average = total / count
return average
calculate_grade([95, 88, 92])
When you run this script in your terminal, execution stops at breakpoint(), presenting the (Pdb) prompt:
> checkout.py(8)calculate_grade()
-> average = total / count
(Pdb)
Essential Pdb Commands Cheat Sheet
| Command | Full Name | What it does |
|---|---|---|
p <var> | Inspects a variable’s value (e.g. p total $\rightarrow$ 275) | |
n | Next | Executes the current line and pauses at the next line |
s | Step | Steps into the function called on this line |
c | Continue | Resumes execution until the next breakpoint or program end |
l | List | Displays surrounding source code lines |
q | Quit | Immediately terminates the program |
At the (Pdb) prompt, you can type any valid Python code! You can test math, modify variables, and inspect object types on the fly.
3. The logging Module: Replacing print()
In production applications (web APIs, automation scripts, background workers), code runs on remote cloud servers where no developer is watching the terminal.
The standard library logging module lets you record diagnostic messages categorized by importance.
The 5 Standard Log Levels
Python organizes logs into five severity tiers:
import logging
# Configure basic logging settings
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logging.debug("Detailed diagnostic information (ignored by default)")
logging.info("System startup successful. Listening on port 8000.")
logging.warning("Memory usage is at 82%. Approaching warning threshold.")
logging.error("Failed to connect to database replica.")
logging.critical("Disk storage 100% full! Shutting down write worker.")
Output:
INFO: System startup successful. Listening on port 8000.
WARNING: Memory usage is at 82%. Approaching warning threshold.
ERROR: Failed to connect to database replica.
CRITICAL: Disk storage 100% full! Shutting down write worker.
Notice that logging.debug(...) was not printed! Because we set level=logging.INFO, Python automatically filtered out lower-priority debug noise. In development, you can flip one setting to level=logging.DEBUG to see everything without editing your code!
4. Writing Logs to a File
In real server deployments, logs should be saved to persistent disk files for subsequent analysis:
import logging
logging.basicConfig(
filename="server.log",
filemode="a", # Append mode (preserves existing logs)
format="%(asctime)s [%(levelname)s] (%(filename)s:%(lineno)d) - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=logging.INFO
)
def authenticate(username, token):
logging.info(f"Login attempt for user: {username}")
if token != "secret_token_123":
logging.warning(f"Failed authentication attempt for: {username}")
return False
return True
authenticate("alex_dev", "wrong_token")
The resulting server.log file on disk contains structured, timestamped audit records:
2026-10-13 14:22:01 [INFO] (auth.py:12) - Login attempt for user: alex_dev
2026-10-13 14:22:01 [WARNING] (auth.py:14) - Failed authentication attempt for: alex_dev
Summary & Stage 7 Capstone
Congratulations on completing Stage 7: Error Handling & Debugging! You now possess the tools to build resilient, reliable software:
- Intercept and recover from failures using try, except, else, and finally.
- Create self-documenting domain errors with custom-exceptions.
- Diagnose and fix bugs using interactive
breakpoint()sessions and productionlogging.
Next, learn how your Python programs can interact with the outside world by reading and writing persistent records in Stage 8, starting with files.