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.
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.
- 1. Why prefer logging over print?
- 2. Bisection finds a bug by…
- 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).
- 1. With the level set to WARNING, which messages appear?
- 2. log.debug('x=%s', x) vs log.debug(f'x={x}'):
- 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.pygives post-mortem inspection at the crash.- IDE debuggers (VS Code, PyCharm) offer conditional breakpoints and watch expressions.
assertfor internal invariants during development;faulthandlerfor segfaults in C extensions.- For numerical code:
np.seterr(all="raise")turns silent NaN/inf into exceptions at the source.
- 1. Why log JSON lines?
- 2. np.seterr(all='raise') helps by…
- 3. In pdb, `w` shows…
Level 3: Advanced
★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.Debugging as search
- In time: if version g is good, version b is bad and badness persists, bisection finds the first bad commit in 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 tests in the best case and 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).
- 1. Bisection requires that 'bad' is…
- 2. A 1-minimal failing input is one where…
- 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.
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
- Python documentation: Logging HOWTO and Logging Cookbook.
- A. Zeller, R. Hildebrandt (2002). “Simplifying and isolating failure-inducing input.” IEEE Transactions on Software Engineering, 28(2).
- A. Zeller (2009). Why Programs Fail: A Guide to Systematic Debugging, 2nd ed. Morgan Kaufmann.
- Git documentation: git-bisect.
- D. J. Agans (2002). Debugging: The 9 Indispensable Rules. AMACOM.