Skip to content

feat(logger): pretty-print JSON when POWERTOOLS_DEV is set #1548

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 6 commits into from
Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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: 7 additions & 1 deletion aws_lambda_powertools/logging/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,15 @@ def __init__(
Key-value to be included in log messages

"""

self.json_deserializer = json_deserializer or json.loads
self.json_default = json_default or str
self.json_serializer = json_serializer or partial(json.dumps, default=self.json_default, separators=(",", ":"))
self.json_indent = (
4 if os.getenv("AWS_SAM_LOCAL", "").lower() == "true" else None
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Use a constant to ease maintaining this later, e.g.

Suggested change
4 if os.getenv("AWS_SAM_LOCAL", "").lower() == "true" else None
PRETTY_INDENT if os.getenv("AWS_SAM_LOCAL", "").lower() == "true" else COMPACT_INDENT

) # indented json serialization when in AWS SAM Local
self.json_serializer = json_serializer or partial(
json.dumps, default=self.json_default, separators=(",", ":"), indent=self.json_indent
)

self.datefmt = datefmt
self.use_datetime_directive = use_datetime_directive
Expand Down
3 changes: 3 additions & 0 deletions docs/core/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,9 @@ As parameters don't always translate well between them, you can pass any callabl
--8<-- "examples/logger/src/bring_your_own_json_serializer.py"
```

???+ info
When your code runs in [AWS SAM local invoke](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-invoke.html) (marked by the `AWS_SAM_LOCAL` env var), Logger's default `json.dumps` will apply indentation by four spaces.

## Testing your code

### Inject Lambda Context
Expand Down
20 changes: 20 additions & 0 deletions tests/functional/test_logger_powertools_formatter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""aws_lambda_logging tests."""
import io
import json
import os
import random
import string
import time
Expand Down Expand Up @@ -288,3 +289,22 @@ def test_log_formatting(stdout, service_name):

# 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]'


def test_log_json_indent_default(stdout, service_name, monkeypatch):
# GIVEN a logger with default settings while NOT in AWS SAM Local
if "AWS_SAM_LOCAL" in os.environ:
monkeypatch.delenv(name="AWS_SAM_LOCAL")
logger = Logger(service=service_name, stream=stdout)
logger.info("Test message")
# THEN the json should not be indented at all (using four blank spaces)
assert " " * 4 not in stdout.getvalue()


def test_log_json_indent_aws_sam_local(stdout, service_name, monkeypatch):
# GIVEN a logger with default settings while in AWS SAM Local
monkeypatch.setenv(name="AWS_SAM_LOCAL", value="true")
logger = Logger(service=service_name, stream=stdout)
logger.info("Test message")
# THEN the json should contain indentation (of four blank spaces)
assert " " * 4 in stdout.getvalue()