Skip to content

Fix: prevent PositionalArgumentsFormatter from crashing on TypeError (#258) - #832

Open
newchannelid432-code wants to merge 3 commits into
hynek:mainfrom
newchannelid432-code:fix/positional-args-typeerror-258
Open

Fix: prevent PositionalArgumentsFormatter from crashing on TypeError (#258)#832
newchannelid432-code wants to merge 3 commits into
hynek:mainfrom
newchannelid432-code:fix/positional-args-typeerror-258

Conversation

@newchannelid432-code

Copy link
Copy Markdown

Fixes #258.

Problem

When using structlog with PositionalArgumentsFormatter, passing a positional argument that does not match a formatting placeholder in the event string (e.g., log.warning('Info message', 'x')) raises an uncaught TypeError: not all arguments converted during string formatting. This crashes the entire application.

Root Cause

In src/structlog/stdlib.py, the formatter directly executes event_dict["event"] %= args without catching formatting exceptions. This differs from the Python standard library logging module, which gracefully catches TypeError and ValueError during formatting to ensure logging never crashes the host application.

Solution

This PR wraps the %= formatting operation in a try...except (TypeError, ValueError) block. If formatting fails due to a user error (mismatched placeholders), the exception is caught and the event string is simply left unformatted. This mimics the fail-safe behavior of stdlib logging and ensures that bad log statements do not result in fatal runtime errors.

A regression test has been added to tests/test_stdlib.py to verify that the processor gracefully handles mismatched placeholders without raising an exception.

Muhamed Fazal PS and others added 3 commits July 29, 2026 22:03
When PositionalArgumentsFormatter encounters a mismatch between the
event string and the positional args (e.g. 'Info message' with args=('x',)),
it raises an uncaught TypeError, crashing the application.

This behavior differs from the Python stdlib logging module, which
gracefully catches formatting errors to prevent logging from taking
down the application.

This patch wraps the formatting operation in a try/except block
catching TypeError and ValueError. If formatting fails, the event
string is left unformatted and the application continues running.
Added a regression test to ensure this behavior is maintained.

Closes hynek#258
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PositionalArgumentsFormatter raises TypeError when postional argument is not a formatting tuple

1 participant