Python · Module 13 · Lesson 21 min read

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: n next line, s step into, c continue, p x print x, q quit.
  • 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.

LevelUse for
DEBUGdetailed developer info
INFOnormal events ("user logged in")
WARNINGsomething odd, still working
ERRORan operation failed
CRITICALthe 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("…") inside except logs the full traceback.

▶️ Runs in the app.

Example

Python
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