An agent’s tool adapter catches an authentication error. Its logging filter replaces the token in the message with [REDACTED]. The emitted entry still contains the token, a few lines lower, inside the exception.
I would reject a redaction test that inspects only record.getMessage(). The acceptance target is the output from every configured handler, after formatting. Python’s standard logging pipeline can append exception and stack information outside that message.
The example below reproduces this with a disposable canary, then shows a second failure involving cached exception text. It uses the real Python logging machinery. It does not call a model or service, and it is not a claim about a defect in Claude Code. The repaired event format is application policy, not an automatic security property of Python logging.
Open the diagram at full size.
The message is only part of the entry
The Python 3.11 Formatter.format documentation describes the order. The formatter computes the message from msg and args. If exception information exists, it formats that information and appends it. Available stack information comes after the exception.
This familiar call therefore has two input paths:
try:
call_tool()
except ValueError:
logger.exception("tool failed: %s", safe_summary)
Even if safe_summary contains no credential, the caught exception may contain a request URL, response body or connection string. A client library can include these in its exception message. The standard traceback formatter includes the exception’s text. This example does not depend on a debugger capturing local variables; the exception value alone is enough.
The OWASP Logging Cheat Sheet lists access tokens, passwords and connection strings among data that should usually not be recorded directly. Logging an authentication failure remains useful. Copying its raw credential into the event creates a separate disclosure.
A message filter may be working exactly as its author intended while leaving that disclosure untouched. The test must reach the handler’s emitted bytes.
Run the canary through a real handler
Download and inspect agent-exception-logging.py. It requires Python 3.11 or later and only the standard library. It makes no network requests and writes no files. Its handlers write into in-memory strings.
python3 agent-exception-logging.py
python3 agent-exception-logging.py --test
python3 -O agent-exception-logging.py --test
The fixture raises a deliberate ValueError containing FAKE_TOKEN_7f91. This is a synthetic marker, not a credential. A weak formatter copies the log record, replaces that marker in getMessage(), clears the message arguments, and delegates to the standard formatter.
The first line contains the replacement. The appended exception still contains the marker. The executed demonstration returned:
{
"message_only_leaks": true,
"exception_override_after_cache_leaks": true,
"safe_event_leaks": false,
"safe_event": {
"error_code": "TOOL_REJECTED",
"event": "tool_failure",
"operation_id": 42
}
}
Seven unique regression tests passed normally and under Python optimisation. They check the message-only leak, cached exception behaviour, exclusion of untrusted fields, preservation of the shared record, leakage through a second unsafe handler, rejection of unknown error codes, and rejection of invalid operation identities. The checks use unittest, so python -O does not remove them.
This is a deterministic logging fixture. It establishes these behaviours for the supplied formatters and records, not a clean bill of health for an installed observability stack.
An earlier formatter can leave cached exception text
Overriding formatException() looks like a direct repair. It can work when that method is called. There is a complication if another formatter has already processed the same record.
Python caches formatted exception information in record.exc_text. Its documentation explicitly warns about this when multiple formatter subclasses customise exception formatting. A later formatter can reuse the cached value instead of recalculating it.
The fixture first formats a record with the ordinary formatter. That populates exc_text with the raw traceback. It then passes the same record, with a harmless message, to a formatter whose formatException() returns [exception omitted]. The cached traceback still appears. Clearing exc_text before the second formatting call makes that particular override take effect, and the regression test verifies both outcomes.
Do not turn that local correction into a general claim that clearing exc_text secures the event. The record can still carry raw arguments, stack information and arbitrary extra fields. Another handler may already have emitted it. A queue or exporter may serialize fields that your console formatter ignores.
If you customise exception formatting, follow the cache guidance and test handler ordering. If handlers need different representations, avoid mutating a shared record in a way that changes another destination’s evidence. The example’s safe formatter reads selected fields without modifying the record.
Emit a small failure event at the adapter boundary
For ordinary operational telemetry, I prefer an explicit event schema at the tool boundary. The demonstration emits only:
{"error_code": "TOOL_REJECTED", "event": "tool_failure", "operation_id": 42}
The formatter constructs a new dictionary. It never serializes record.__dict__, calls getMessage(), formats the exception or appends stack information. It accepts an error code from a fixed set and requires a positive integer operation identity. It also rejects booleans, which Python otherwise treats as integers.
Those fields have a deliberately narrow provenance in the fixture. The coordinator assigns operation ID 42; it does not copy an arbitrary request header. The adapter assigns TOOL_REJECTED; it does not accept an upstream exception message as the code. Allowlisting field names is insufficient if a supposedly safe field can contain arbitrary external text.
In a real adapter, classify failures at the catch site using the library’s documented exception types or status fields. Map them to your own stable codes. Do not infer retry safety from a friendly code alone: a timeout can leave the effect unknown, as the worker-thread timeout example demonstrates.
The supplied formatter is for a dedicated failure-event sink. It expects its fields to exist and rejects invalid values. It is not a drop-in formatter for every third-party library logger. Test how your service handles rejected telemetry records, including logging’s error-reporting path. Do not respond to a schema failure by printing the rejected record into an unrestricted fallback log.
A production implementation should usually construct the safe event before handing data to an asynchronous queue or exporter. Formatting safely at the final console does not stop an earlier transport from retaining the raw record.
Test the other destinations too
One test sends the same record to the safe formatter and then to an ordinary formatter. The first output excludes the canary. The second leaks it. Passing the safe sink test therefore does not certify the logger configuration.
Inventory the handlers attached to the application logger and its ancestors, including propagation to the root logger. Then test the deployed paths: console collection, file rotation, exception reporting and any queue-backed exporter. Keep those tests separate from the fixture’s in-memory results; none of those integrations has been executed here.
Use distinct disposable markers in the message arguments, exception text and structured extra fields. Include chained exceptions if your adapters use them. Inspect the final captured payloads rather than assuming that the console view represents what an exporter stores. Keep test payloads synthetic so that a failed redaction test does not disclose a real credential.
There are two separate checks. Log framing prevents tool output from forging another entry. Field selection controls what data enters a legitimate entry. JSON encoding can preserve the first boundary while faithfully storing a secret that violates the second.
Detailed diagnostics may still be necessary. If you retain raw exceptions, give that store its own access policy, retention and incident procedure. Do not silently route raw copies to an ordinary tracing account. The earlier trace-access article covers the separate question of who can resolve restricted evidence after it has been stored.
For the wider tool-boundary and review workflow, see my Claude Code book, available as a Kindle edition on Amazon UK.
Add a canary-bearing exception to one adapter test. Capture every configured destination and require the ordinary telemetry outputs to contain the approved error code and operation identity without the canary.