Product case study · December 1, 2026
Ask Claude Code to recover a missing Python traceback
Recover missing Python tracebacks with a scoped Claude Code repair. Test exception records and formatted output without changing return behavior.

Test the exception information and rendered log, not just whether an error message exists.
Your batch job logs ERROR: count conversion failed: invalid literal..., then carries on. You know a value was bad, but the log has lost the call stack that would help you locate the failure.
In this exercise, Claude Code gets a narrow job: preserve the exception traceback while keeping the function’s existing return values. The acceptance test must inspect more than the word ERROR. A message can have the right severity and still omit the evidence you need.
Bring Python 3.10 or newer, Bash on Linux, macOS or WSL, and an installed, signed-in Claude Code. The Python fixture and reference repair were tested locally; the Claude prompt is an authored exercise, not a recorded agent run. Official documentation was checked December 1, 2026. All input below is fictional and stays local.
Reproduce the missing evidence
Create a practice folder and save the deliberately incomplete function:
trace_lab=$(mktemp -d /tmp/claude-traceback.XXXXXX)
cd "$trace_lab"
cat > count_reader.py <<'PY'
import logging
logger = logging.getLogger("count_lab")
def read_count(raw):
try:
return int(raw)
except ValueError as error:
logger.error("count conversion failed: %s", error)
return None
if __name__ == "__main__":
logging.basicConfig(level=logging.ERROR, format="%(levelname)s: %(message)s")
print(read_count("not-a-count"))
PY
python3 count_reader.py
The program prints an error message and None, but no traceback. Logging normally goes to standard error here; print writes to standard output, so their display order is not the acceptance criterion.
An ERROR level does not automatically attach the active exception. Python documents Logger.exception for use inside an exception handler; it includes exception information at ERROR level. logger.error(..., exc_info=True) is another documented way to include it. Neither option repairs the invalid input or changes whether your function returns or raises.
Write the contract before asking for a fix
Save this as SPEC.md:
Only count_reader.py may change.
read_count("12") must return 12 without logging an error.
read_count("not-a-count") must return None and emit one ERROR record.
That record must retain the active ValueError and a traceback.
A standard logging.Formatter must render the traceback and read_count frame.
Keep the message prefix "count conversion failed".
Keep catching ValueError only; do not add retries or change error propagation.
Do not add dependencies, handlers inside read_count, or print-based diagnostics.
Do not edit test_count_reader.py.
This deliberately preserves the existing recovery policy. In a real job, returning None might be the wrong policy; decide that separately before asking an agent to change it. The Python logging HOWTO distinguishes reporting an error from reporting an error that a program suppresses.
Save this as test_count_reader.py:
import logging
import unittest
from count_reader import read_count
class CountLoggingTests(unittest.TestCase):
def capture_failure(self):
with self.assertLogs("count_lab", level="ERROR") as captured:
result = read_count("not-a-count")
self.assertIsNone(result)
self.assertEqual(len(captured.records), 1)
record = captured.records[0]
self.assertEqual(record.levelno, logging.ERROR)
self.assertIn("count conversion failed", record.getMessage())
return record
def test_success_stays_quiet(self):
with self.assertNoLogs("count_lab", level="ERROR"):
self.assertEqual(read_count("12"), 12)
def test_failure_keeps_exception(self):
record = self.capture_failure()
self.assertIsNotNone(record.exc_info)
kind, error, traceback = record.exc_info
self.assertIs(kind, ValueError)
self.assertIsInstance(error, ValueError)
self.assertIsNotNone(traceback)
def test_formatter_keeps_traceback(self):
record = self.capture_failure()
text = logging.Formatter("%(levelname)s: %(message)s").format(record)
self.assertIn("Traceback (most recent call last):", text)
self.assertIn("in read_count", text)
self.assertIn("ValueError:", text)
Run the baseline:
python3 --version
python3 -m unittest -v test_count_reader
The local baseline ran three tests: the valid-input check passed, and both traceback checks failed. Keep that failure output. It distinguishes a meaningful repair from an agent simply saying the logging looks better.
assertLogs exposes captured records as well as formatted output. Here we inspect the record and apply a formatter ourselves. assertNoLogs, used for the successful input, requires Python 3.10 or newer.
Give Claude Code the bounded task
Start claude inside the practice folder and paste:
Read SPEC.md, count_reader.py and test_count_reader.py.
Run python3 -m unittest -v test_count_reader and report the actual baseline.
Explain why an ERROR message can exist without exception information.
Change only count_reader.py to satisfy SPEC.md.
Keep the tests fixed. Do not install packages, commit or delegate.
Run the same tests again and show the changed lines.
Finish by running python3 count_reader.py and reporting what it emits.
Distinguish local handler output from delivery to an external log service.
Anthropic recommends giving Claude a concrete check and reviewing the result against a specification in its best-practices guide. Review the requested tool access for this folder; the prompt itself does not enforce a filesystem boundary.
If Claude changes the expected assertions, stop that edit and restore the published test file in this disposable lab. If it adds a handler on every function call, point back to the contract: a traceback problem does not require rebuilding the logging configuration.
Review the repair and verify independently
The reference repair changes just the logging call inside except:
logger.exception("count conversion failed: %s", error)
Leave the return None and exception type unchanged. This reference repair passed all three tests locally. Exit Claude and rerun the same test command yourself, then inspect the combined output:
python3 -m unittest -v test_count_reader
python3 count_reader.py 2>&1
Look for the message prefix, Traceback (most recent call last):, a frame in read_count, the ValueError line, and the printed None. File paths and line numbers will vary. Do not require an exact machine-specific traceback string.
There are two tempting repairs to reject. logger.error(str(error)) still logs only a message. Moving logger.exception after the exception handler loses the active exception context this exercise relies on. Keep the call within except.
Know what the test proves
The tests prove that this function retains exception information and that a standard formatter can render it. The direct command also checks the fixture’s configured console handler. They do not prove that a production collector, JSON formatter or dashboard preserves those fields.
If production still shows only a message, follow one synthetic failure through the configured handler, serialized record and destination. Compare where the traceback disappears. If you see duplicate entries, investigate handlers and propagation separately; do not remove exception information to hide the duplicates.
Before using this pattern with real inputs, inspect what the exception message contains. This toy conversion includes the rejected string in the ValueError message. Use synthetic data when sharing the exercise output, and apply your application’s redaction rules before forwarding real logs to an agent or outside service.
Continue with the project-session lesson if you need help opening a scoped workspace. The useful handoff from this lab is small: the unchanged contract, the failing baseline, the one-line repair and the passing checks.
Sources
Checked December 1, 2026:
- Python: Logging reference — exception information, ERROR-level logging and formatter behavior.
- Python: Logging HOWTO — choosing logging behavior and configuring output.
- Python: unittest — captured log records, no-log assertions and command-line execution.
- Anthropic: Claude Code best practices — concrete verification commands and review against a specification.
Put this to work
How to distinguish an ERROR-level message from a log record containing exception information.
Try
Ask Claude Code to repair one logging call without changing the function's return behavior.
Prove it worked
Run three local tests before and after the repair, then inspect the emitted traceback.
Keep in view
- Reproduce a log that keeps the error message but loses its traceback.
- Give Claude Code a fixed test contract for exception evidence.
- Check both the captured record and the text a handler emits.