diff --git a/haystack/logging.py b/haystack/logging.py index a5b8ef84d..fb0149a03 100644 --- a/haystack/logging.py +++ b/haystack/logging.py @@ -190,7 +190,10 @@ def patch_make_records_to_use_kwarg_string_interpolation(original_make_records: @functools.wraps(original_make_records) def _wrapper(name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None) -> Any: safe_extra = extra or {} - interpolated_msg = msg.format(**safe_extra) + try: + interpolated_msg = msg.format(**safe_extra) + except (KeyError, ValueError): + interpolated_msg = msg return original_make_records(name, level, fn, lno, interpolated_msg, (), exc_info, func, extra, sinfo) return _wrapper diff --git a/releasenotes/notes/fix-logs-containing-json-1393a00b4904f996.yaml b/releasenotes/notes/fix-logs-containing-json-1393a00b4904f996.yaml new file mode 100644 index 000000000..618dbc78e --- /dev/null +++ b/releasenotes/notes/fix-logs-containing-json-1393a00b4904f996.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fixes logs containing JSON data getting lost due to string interpolation. diff --git a/test/test_logging.py b/test/test_logging.py index 2663b79e9..ce9607e04 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -490,6 +490,28 @@ class TestCompositeLogger: "module": "test.test_logging", } + def test_log_json_content(self, capfd: LogCaptureFixture) -> None: + haystack_logging.configure_logging(use_json=True) + + logger = haystack_logging.getLogger(__name__) + logger.setLevel(logging.DEBUG) + + logger.log(logging.DEBUG, 'Hello, structured: {"key": "value"}', key="logging", key1="value1", key2="value2") + + output = capfd.readouterr().err + parsed_output = json.loads(output) + + assert parsed_output == { + "event": 'Hello, structured: {"key": "value"}', + "key": "logging", + "key1": "value1", + "key2": "value2", + "level": "debug", + "timestamp": ANY, + "lineno": ANY, + "module": "test.test_logging", + } + def test_log_with_string_cast(self, capfd: LogCaptureFixture) -> None: haystack_logging.configure_logging(use_json=True)