Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions shared/logging/src/airflow_shared/logging/structlog.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,24 @@ def drop_positional_args(logger: Any, method_name: Any, event_dict: EventDict) -
return event_dict


def _normalize_positional_args(logger: Any, method_name: Any, event_dict: EventDict) -> EventDict:
"""
Convert dict positional args to their string representation.

Python's ``LogRecord.__init__`` converts ``({'key': val},)`` into ``{'key': val}``
(a bare dict). When ``ProcessorFormatter`` stores that dict as ``positional_args``,
structlog's ``PositionalArgumentsFormatter`` crashes because it expects a tuple.

Logging a dict directly (e.g. ``logger.warning("msg %s", {"a": 10})``) is not valid.
The correct way is ``logger.warning("msg %s", str({"a": 10}))``. This processor
applies that conversion automatically so that callers do not crash.
"""
args = event_dict.get("positional_args")
if isinstance(args, dict):
event_dict["positional_args"] = (str(args),)
return event_dict


# This is a placeholder fn, that is "edited" in place via the `suppress_logs_and_warning` decorator
# The reason we need to do it this way is that structlog caches loggers on first use, and those include the
# configured processors, so we can't get away with changing the config as it won't have any effect once the
Expand Down Expand Up @@ -268,6 +286,7 @@ def structlog_processors(
timestamper,
structlog.contextvars.merge_contextvars,
structlog.processors.add_log_level,
_normalize_positional_args,
structlog.stdlib.PositionalArgumentsFormatter(),
logger_name,
redact_jwt,
Expand Down
41 changes: 39 additions & 2 deletions shared/logging/tests/logging/test_structlog.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,8 +389,6 @@ def test_json_exc(structlog_config, get_logger, monkeypatch):
1 / 0
except ZeroDivisionError:
get_logger("logger").exception("Error")
written = bio.getvalue()

written = json.load(bio)
assert written == {
"event": "Error",
Expand Down Expand Up @@ -623,3 +621,42 @@ def test_without_file_uses_py_warnings_logger(self):
_showwarning("some warning", UserWarning, "foo.py", 1)

mock_get_logger.assert_called_once_with("py.warnings")


@pytest.mark.parametrize(
("get_logger", "config_kwargs", "expected_substring"),
[
pytest.param(
logging.getLogger,
{},
"Info message {'a': 10}",
id="stdlib-console",
),
pytest.param(
logging.getLogger,
{"json_output": True},
"Info message {'a': 10}",
id="stdlib-json",
),
],
)
def test_dict_as_positional_arg(structlog_config, get_logger, config_kwargs, expected_substring):
"""Regression test for Issue #62201: dict as positional arg must not crash."""
with structlog_config(colors=False, **config_kwargs) as sio:
logger = get_logger("my.logger")
logger.warning("Info message %s", {"a": 10})

output = sio.getvalue() if hasattr(sio, "getvalue") else sio.read()
if isinstance(output, bytes):
output = output.decode("utf-8")
assert expected_substring in output


def test_multiple_positional_args_still_work(structlog_config):
"""Ensure normal positional args formatting is not broken by the dict-arg fix."""
with structlog_config(colors=False) as sio:
logger = logging.getLogger("my.logger")
logger.warning("Values: %s %d %s", "hello", 42, "world")

written = sio.getvalue()
assert "Values: hello 42 world" in written
Loading