Skip to content

Module 20 · Building Real Python Applications — topic 11 of 13

Debugging applications

Debugging beyond single functions: configuring logging per component, reproducing problems from recorded input, isolating the failing step, and bisecting data to find the record that breaks a report.

Beginner 10 min read·Lesson 304 of 306 in Python Programming

Learning objectives

  • Configure logging for different components
  • Reproduce bugs by replaying recorded input
  • Narrow down failing data by bisection

Definition

Debugging an application means locating faults in a system of interacting components. It relies on logs that show what each component did, reproducible inputs, and techniques for narrowing a problem down to one component, step or record.

Introduction

'The monthly report crashes for one user' is a typical application bug: the code worked in tests, but some combination of data and steps breaks it.

Why it matters

Application bugs are often intermittent or data-dependent. Logging, replay and bisection turn them into ordinary, reproducible bugs.

Detailed explanation

Give each component its own logger (logging.getLogger("tracker.storage")) so you can turn on detailed logs for one part only.

Log important events with context: which command, which file, how many records — but never passwords or personal data.

Record the inputs that lead to a bug (commands, data files) so the problem can be replayed exactly, again and again.

Replay the steps one by one and report the first step that fails, with its input and exception.

Isolate the component: if storage loads correct data, the bug is in the logic or output; test each layer separately.

When a large data set breaks processing, bisect it: run on half the data, keep the failing half, and repeat until one record remains.

Once found, write a failing test with that minimal input before fixing.

Keep debugging aids (log statements, replay scripts) — they will help with the next bug.

Syntax

Python
import logging
log = logging.getLogger("tracker.storage")
logging.getLogger("tracker.storage").setLevel(logging.DEBUG)
log.debug("loaded %d expenses from %s", len(items), path)
  • One logger per component.
  • Replay recorded input.
  • Bisect failing data.

Code examples

Logging per component

Python
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(name)s %(levelname)s %(message)s", force=True)
storage_log = logging.getLogger("tracker.storage")
ui_log = logging.getLogger("tracker.ui")
storage_log.setLevel(logging.DEBUG)
storage_log.debug("loading expenses.json")
ui_log.debug("hidden: ui debug details")
ui_log.info("showing 3 expenses")
Output
tracker.storage DEBUG loading expenses.json
tracker.ui INFO showing 3 expenses

Replaying recorded input

Python
recorded = ["add 250 food", "add x travel", "report"]
def process(cmd, state):
parts = cmd.split()
if parts[0] == "add":
state.append((float(parts[1]), parts[2]))
elif parts[0] == "report":
return sum(a for a, _ in state)
state = []
for i, cmd in enumerate(recorded, 1):
try:
process(cmd, state)
except Exception as e:
print(f"step {i} {cmd!r} failed: {type(e).__name__}: {e}")
break
Output
step 2 'add x travel' failed: ValueError: could not convert string to float: 'x'

More examples

Bisecting data to find a bad record

Python
records = [{"amount": str(10 * i)} for i in range(1, 101)]
records[63]["amount"] = "N/A"
def report(rows):
return sum(float(r["amount"]) for r in rows)
def find_bad(rows):
lo, hi = 0, len(rows)
checks = 0
while hi - lo > 1:
mid = (lo + hi) // 2
checks += 1
try:
report(rows[lo:mid])
lo = mid # left half is fine; the problem is on the right
except ValueError:
hi = mid # the problem is in the left half
return lo, checks
bad, checks = find_bad(records)
print("bad record at index", bad, records[bad], "found in", checks, "checks")
Output
bad record at index 63 {'amount': 'N/A'} found in 7 checks

Step-by-step explanation

  • The report crashes somewhere among 100 records.
  • Each check runs the report on half of the remaining range and keeps the half that fails.
  • Seven checks pinpoint the one bad record — the same halving idea as binary search.

Expected output

Running “Bisecting data to find a bad record” prints exactly:

TextOutput
bad record at index 63 {'amount': 'N/A'} found in 7 checks

Practical applications

  • Finding the one malformed row in a large import.
  • git bisect finding the commit that introduced a bug.

Best practices

  • Use named loggers per component.
  • Record and replay failing inputs.
  • Bisect large data sets.

Common mistakes

Logging personal data

Avoid

log.info("login %s with password %s", user, password)

Prefer

log.info("login attempt for user id %s", user_id)

Logs are often shared and stored; keep secrets and personal data out.

Important notes

  • Error-tracking services collect exceptions with context from deployed applications automatically.

Key takeaways

  • Per-component logging shows what each part did.
  • Replay recorded input to reproduce bugs.
  • Bisection finds failing records quickly.

Try it yourself

  1. 1
    Add DEBUG logging to the storage layer of your tracker and switch it on with an environment variable.
  2. 2
    Write a replay script that reads commands from a file and reports the first failure.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions cover the “Building Real Python Applications” module. Answers and explanations are revealed after you submit.

  • AdvancedWhat does MVP stand for when planning an application?
  • AdvancedWhere should input validation ideally happen?
  • AdvancedWhat is printed?
Practise this module