Foundations to Frontier
Tests
C. Programming, Tools and HPC › C2 Software Engineering for Research

Logging and Debugging

When a long simulation, a training run or a robot misbehaves, logs are your flight recorder and debugging is a systematic search. This topic covers Python's logging module (loggers, levels, handlers, formatters, structured JSON logs, logging exceptions, not using print), debugging tools (pdb/breakpoint, post-mortem, IDE debuggers, assertions, faulthandler), and scientific debugging: reproduce, form hypotheses, bisect in time (git bisect) and in input (delta debugging). In the exercises you build structured JSON logging for a ground-station pass and query it, then implement git-bisect and Zeller's ddmin to localize a regression and shrink a crashing 1024-packet telemetry stream to its 2-packet cause.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A flight recorder for your code

An aircraft’s black box records what happened so investigators can work out what went wrong. Logging is the same for programs: instead of scattering print statements that you delete later, you record timestamped events (“battery voltage low”, “solver did not converge”) with a severity level, to a file you can search afterwards. Debugging is detective work: reproduce the problem, then narrow down where it starts, ideally by halving the suspects each step.

git bisect: find the commit that broke it
0 (good)63 (bad)
suspects: commits 1–63 (63 left) · tests so far 0 · bisect needs ⌈log₂ 63⌉ = 6 tests; checking one by one would need up to 62
Bisection works whenever "bad" is monotone in time: once a commit is broken, later ones are too. git bisect automates it (git bisect run executes your test script at each step). The same halving idea powers delta debugging, which shrinks a huge failing input (a crash-inducing telemetry file) to the few bytes that matter. Debugging is search: make the search space small, then halve it.
Why engineers care

Spacecraft anomalies are diagnosed almost entirely from telemetry and event logs, because you can’t attach a debugger to a probe 200 million km away. The same discipline (structured, levelled, timestamped logs plus systematic bisection) turns week-long debugging hunts in research code into hours.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Why prefer logging over print?
  2. 2. Bisection finds a bug by…
  3. 3. The first step in debugging is to…

Level 1: Beginner

★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.

The logging module

import logging
log = logging.getLogger(__name__)           # one logger per module, named hierarchically

def propagate(state, dt):
    log.debug("step dt=%g", dt)             # lazy formatting: cheap when DEBUG is off
    if not converged:
        log.warning("solver did not converge after %d iterations", it)

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")

Levels: DEBUG < INFO < WARNING < ERROR < CRITICAL. The logger’s level filters messages, and handlers (console, file, rotating file, syslog) decide where they go. Libraries should only create loggers; applications configure handlers.

Exceptions

log.exception("failed to parse frame") inside except records the traceback. Don’t swallow exceptions silently: either handle them meaningfully or re-raise with context (raise RuntimeError(...) from err).

📝 Quick check (Level 1)
0/3 answered
  1. 1. With the level set to WARNING, which messages appear?
  2. 2. log.debug('x=%s', x) vs log.debug(f'x={x}'):
  3. 3. Inside except, which call records the traceback?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

Structured logging

Log key-value fields (extra={"subsystem": "EPS", "volts": 26.9}) and emit JSON lines, so logs can be filtered and aggregated by machines: count errors per subsystem, plot voltages from the log, correlate events across services. Include run IDs (C2.4) in every record.

Debugging tools

  • breakpoint() drops into pdb: next, step, continue, p expr, where, up/down.
  • python -m pdb -c continue script.py gives post-mortem inspection at the crash.
  • IDE debuggers (VS Code, PyCharm) offer conditional breakpoints and watch expressions.
  • assert for internal invariants during development; faulthandler for segfaults in C extensions.
  • For numerical code: np.seterr(all="raise") turns silent NaN/inf into exceptions at the source.
🐍 Exercise 1: structured logs for a ground-station pass
Write a JSON-lines log formatter that includes structured extra fields and exception names, configure a logger writing to an in-memory stream, log a simulated pass (AOS, voltages with an undervoltage warning, a parsing exception, LOS), then parse the log to count records per level and list the alerts. Check that DEBUG lines appear only when enabled.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Why log JSON lines?
  2. 2. np.seterr(all='raise') helps by…
  3. 3. In pdb, `w` shows…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.
  • In time: if version g is good, version b is bad and badness persists, bisection finds the first bad commit in ⌈log⁡2(b−g)⌉\lceil\log_2(b - g)\rceil tests.
  • In input: Zeller’s delta debugging (ddmin) splits a failing input into n chunks, tests each chunk and each complement, recurses on whichever still fails, and doubles n otherwise. It returns a 1-minimal failing input (removing any single element makes it pass) in O(log⁡n)O(\log n) tests in the best case and O(n2)O(n^2) in the worst.
  • In space: comment out or stub halves of a pipeline, or compare intermediate arrays against a reference implementation.

Habits that make debugging possible

Seed everything (C2.4), log configuration and versions at start-up, fail fast on invalid input, keep a minimal reproducible example, and turn every fixed bug into a regression test (C2.2).

📝 Quick check (Level 3)
0/3 answered
  1. 1. Bisection requires that 'bad' is…
  2. 2. A 1-minimal failing input is one where…
  3. 3. After fixing a bug you should…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Logs and debugging, measured

Exercise 1. The pass produces 4 INFO, 1 WARNING (EPS undervoltage at 26.9 V) and 1 ERROR (OBC mode-parse KeyError, with the exception name recorded). Each line is JSON with its structured fields. Enabling DEBUG adds the raw-frame line, without code changes.

Exercise 2. Bisection finds commit 637 of 1000 in 10 tests (⌈log₂ 999⌉). A parser crashes when a CRC-error packet (0xEE = 238) is followed by an empty one. ddmin and one-at-a-time removal both find the 2-packet trigger [238, 0], but the costs differ:

stream length ddmin tests one-at-a-time tests
16 19 34
64 22 146
256 25 594
1024 28 2386

ddmin grows by only about 3 tests per 4× more data here; the naive method grows linearly.

🐍 Exercise 2 (research): bisect in time, minimize in input
Implement git-bisect's binary search over a commit range and Zeller's ddmin. Use ddmin and a naive one-at-a-time minimizer to shrink crashing telemetry streams of increasing length to the failure-inducing packets, and compare how many tests each needs.

Logging and debugging in AI, robotics and aerospace

  • Telemetry and event logs for anomaly investigation; onboard logs downlinked with priority levels.
  • ROS 2 logging (rclpy loggers, rosbag recordings) for robot debugging and replay.
  • Experiment tracking (structured metrics logs) for ML training runs.
  • Fuzzing plus delta debugging to harden telemetry and command parsers against malformed packets.

References

  1. Python documentation: Logging HOWTO and Logging Cookbook.
  2. A. Zeller, R. Hildebrandt (2002). “Simplifying and isolating failure-inducing input.” IEEE Transactions on Software Engineering, 28(2).
  3. A. Zeller (2009). Why Programs Fail: A Guide to Systematic Debugging, 2nd ed. Morgan Kaufmann.
  4. Git documentation: git-bisect.
  5. D. J. Agans (2002). Debugging: The 9 Indispensable Rules. AMACOM.