Knowledge card L2 · Context engineering informational

Add Logging Before You Let Claude Guess

What it is

A debugging pattern for bugs with no error — wrong output, silent misbehaviour — where you ask Claude to add temporary, targeted logging around the suspect path first, run it, and paste the output back before any fix is attempted.

observe, then fix01Add targeted logs02Run once03Read the values04Fix the real gap
Turn an invisible bug into data before touching the logic.

Why it works

When there's no stack trace, both you and Claude are guessing at hidden state. Instrumentation replaces the guess with evidence: the actual value at each step, in the real run. Claude is good at deciding what to log to distinguish competing theories, and once it sees the values it stops proposing plausible-but-wrong fixes.

When to use it

Silent failures, wrong numbers, off-by-something results, state that's correct in isolation but wrong in combination, and anything you can't reproduce in a test yet but can run.

When not to use it

When a stack trace already pins the failure, or in hot paths where logging changes timing enough to hide the bug. There, a failing test or a debugger breakpoint is cleaner.

Prompt

This produces the wrong result but throws no error: <describe expected vs actual>.
Here is the relevant code: <paste>.

Before proposing a fix, add temporary logging that would let us see exactly where the value first goes wrong — log the inputs and the value at each transformation, clearly labelled. I'll run it and paste the output. Then diagnose from the actual values, not a guess.

Example

A total comes out slightly low. Claude adds four labelled logs across the reduce. The output shows the running total is right until a discount line, where a string "10" is concatenated instead of added. The fix — parse the value — is now obvious and provably correct, and you delete the logs.

Advanced version

Ask Claude to make the logs assertive: instead of printing values, have it insert temporary asserts encoding what it believes should be true at each step. The first assert to fire names the exact boundary where reality diverges from the theory.

Common mistakes

  • Letting the debug logging ship — ask Claude to mark it clearly and remove it once the bug is found.
  • Logging so much that the real signal drowns; a few labelled values beat a wall of output.
  • Accepting a fix before actually running the instrumented version — the whole point is to look before you leap.

Related