Skip to content

fix(logger): Support .info("foo %s", "bar") formatting #426

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 7, 2021
Merged
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
3 changes: 3 additions & 0 deletions aws_lambda_powertools/logging/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,9 @@ def _extract_log_message(self, log_record: logging.LogRecord) -> Union[Dict[str,
if isinstance(message, dict):
return message

if log_record.args: # logger.info("foo %s", "bar") requires formatting
return log_record.getMessage()

if isinstance(message, str): # could be a JSON string
try:
message = self.json_deserializer(message)
Expand Down
13 changes: 13 additions & 0 deletions tests/functional/test_logger_powertools_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,3 +275,16 @@ def test_logging_various_primitives(stdout, service_name, message):
# THEN it should raise no serialization/deserialization error
logger.info(message)
json.loads(stdout.getvalue())


def test_log_formatting(stdout, service_name):
# GIVEN a logger with default settings
logger = Logger(service=service_name, stream=stdout)

# WHEN logging a message with formatting
logger.info('["foo %s %d %s", null]', "bar", 123, [1, None])

log_dict: dict = json.loads(stdout.getvalue())

# THEN the formatting should be applied (NB. this is valid json, but hasn't be parsed)
assert log_dict["message"] == '["foo bar 123 [1, None]", null]'