Debugging & Logging
Reading tracebacks
Start at the last line (the error type and message), then read upwards to find your file and line number.
Debugging tools
print(f"{x=}")for quick checks.breakpoint()pauses the program and opens the pdb debugger. Commands:nnext line,sstep into,ccontinue,p xprintx,qquit.- IDE debuggers (VS Code, PyCharm) let you set breakpoints by clicking.
Why logging beats print
logging has levels, timestamps, and can write to files, and you can turn messages on or off without deleting code.
| Level | Use for |
|---|---|
DEBUG | detailed developer info |
INFO | normal events ("user logged in") |
WARNING | something odd, still working |
ERROR | an operation failed |
CRITICAL | the app can't continue |
Best practices
- One logger per module:
logger = logging.getLogger(__name__). - Pass values as arguments:
logger.info("Saved %s rows", count). The text is only built if the message is shown. logger.exception("…")insideexceptlogs the full traceback.
▶️ Runs in the app.
Example
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(name)s: %(message)s",
)
logger = logging.getLogger("calculator")
def divide(a, b):
logger.debug("divide(%s, %s)", a, b) # hidden at INFO level
if b == 0:
logger.warning("Division by zero attempted with a=%s", a)
raise ZeroDivisionError("b must not be 0")
result = a / b
logger.info("Result: %s", result)
return result
divide(10, 4)
try:
divide(1, 0)
except ZeroDivisionError:
logger.exception("Calculation failed") # includes the traceback
# Quick debugging
total = 42
print(f"{total=}") # total=42
# breakpoint() # uncomment on a computer to open the debugger