Skip to content

Commit aba76c3

Browse files
fix(logger): keep string messages that are valid JSON scalars as strings
1 parent 379929b commit aba76c3

2 files changed

Lines changed: 38 additions & 2 deletions

File tree

‎aws_lambda_powertools/logging/formatter.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -357,9 +357,13 @@ def _extract_log_message(self, log_record: logging.LogRecord) -> dict[str, Any]
357357

358358
if isinstance(message, str): # could be a JSON string
359359
try:
360-
message = self.json_deserializer(message)
360+
decoded = self.json_deserializer(message)
361361
except (json.decoder.JSONDecodeError, TypeError, ValueError):
362-
pass
362+
return message
363+
364+
# only JSON objects and arrays become structured output; scalars like "null" or "123" stay strings
365+
if isinstance(decoded, (dict, list)):
366+
return decoded
363367

364368
return message
365369

‎tests/functional/logger/required_dependencies/test_logger_powertools_formatter.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,38 @@ def test_with_json_message(stdout, service_name):
122122
assert msg == log_dict["message"]
123123

124124

125+
@pytest.mark.parametrize("msg", ["null", "true", "123", "1e3", '"quoted"', "NaN"])
126+
def test_with_json_scalar_string_message_stays_string(stdout, service_name, msg):
127+
# GIVEN a logger with default settings
128+
logger = Logger(service=service_name, stream=stdout)
129+
130+
# WHEN logging a string that is also a valid JSON scalar
131+
logger.info(msg)
132+
133+
# THEN the message is kept as the original string
134+
log_dict = json.loads(stdout.getvalue())
135+
assert log_dict["message"] == msg
136+
137+
138+
@pytest.mark.parametrize(
139+
"msg, expected",
140+
[
141+
('{"order_id": 123, "items": ["a", "b"]}', {"order_id": 123, "items": ["a", "b"]}),
142+
('["a", "b"]', ["a", "b"]),
143+
],
144+
)
145+
def test_with_json_object_or_array_string_message_is_decoded(stdout, service_name, msg, expected):
146+
# GIVEN a logger with default settings
147+
logger = Logger(service=service_name, stream=stdout)
148+
149+
# WHEN logging a string that is a JSON object or array
150+
logger.info(msg)
151+
152+
# THEN the message is decoded into structured output
153+
log_dict = json.loads(stdout.getvalue())
154+
assert log_dict["message"] == expected
155+
156+
125157
def test_with_unserializable_value_in_message(stdout, service_name):
126158
logger = Logger(service=service_name, level="DEBUG", stream=stdout)
127159

0 commit comments

Comments
 (0)