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
8 changes: 6 additions & 2 deletions aws_lambda_powertools/logging/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,9 +357,13 @@ def _extract_log_message(self, log_record: logging.LogRecord) -> dict[str, Any]

if isinstance(message, str): # could be a JSON string
try:
message = self.json_deserializer(message)
decoded = self.json_deserializer(message)
except (json.decoder.JSONDecodeError, TypeError, ValueError):
pass
return message

# only JSON objects and arrays become structured output; scalars like "null" or "123" stay strings
if isinstance(decoded, (dict, list)):
return decoded

return message

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,38 @@ def test_with_json_message(stdout, service_name):
assert msg == log_dict["message"]


@pytest.mark.parametrize("msg", ["null", "true", "123", "1e3", '"quoted"', "NaN"])
def test_with_json_scalar_string_message_stays_string(stdout, service_name, msg):
# GIVEN a logger with default settings
logger = Logger(service=service_name, stream=stdout)

# WHEN logging a string that is also a valid JSON scalar
logger.info(msg)

# THEN the message is kept as the original string
log_dict = json.loads(stdout.getvalue())
assert log_dict["message"] == msg


@pytest.mark.parametrize(
"msg, expected",
[
('{"order_id": 123, "items": ["a", "b"]}', {"order_id": 123, "items": ["a", "b"]}),
('["a", "b"]', ["a", "b"]),
],
)
def test_with_json_object_or_array_string_message_is_decoded(stdout, service_name, msg, expected):
# GIVEN a logger with default settings
logger = Logger(service=service_name, stream=stdout)

# WHEN logging a string that is a JSON object or array
logger.info(msg)

# THEN the message is decoded into structured output
log_dict = json.loads(stdout.getvalue())
assert log_dict["message"] == expected


def test_with_unserializable_value_in_message(stdout, service_name):
logger = Logger(service=service_name, level="DEBUG", stream=stdout)

Expand Down