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 2 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: 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 = (
constants.PRETTY_INDENT if os.getenv("POWERTOOLS_DEV", "").lower() == "true" else constants.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 aws_lambda_powertools/shared/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,6 @@
"cold_start",
"xray_trace_id",
]

PRETTY_INDENT: int = 4
COMPACT_INDENT = None
3 changes: 3 additions & 0 deletions docs/core/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,9 @@ If you prefer configuring it separately, or you'd want to bring this JSON Format
| **`log_record_order`** | set order of log keys when logging | `["level", "location", "message", "timestamp"]` |
| **`kwargs`** | key-value to be included in log messages | `None` |

???+ info
When `POWERTOOLS_DEV` env var is present and set to `"true"`, Logger's default serializer (`json.dumps`) will pretty-print log messages for easier readability.

```python hl_lines="2 7-8" title="Pre-configuring Lambda Powertools Formatter"
--8<-- "examples/logger/src/powertools_formatter_setup.py"
```
Expand Down
21 changes: 21 additions & 0 deletions tests/functional/test_logger_powertools_formatter.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
"""aws_lambda_logging tests."""
import io
import json
import os
import random
import string
import time

import pytest

from aws_lambda_powertools import Logger
from aws_lambda_powertools.shared import constants


@pytest.fixture
Expand Down Expand Up @@ -288,3 +290,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_compact_indent(stdout, service_name, monkeypatch):
# GIVEN a logger with default settings and WHEN POWERTOOLS_DEV is not set
if "POWERTOOLS_DEV" in os.environ:
monkeypatch.delenv(name="POWERTOOLS_DEV")
logger = Logger(service=service_name, stream=stdout)
logger.info("Test message")
# THEN the json should not be indented using constant.PRETTY_INDENT blank spaces
assert " " * constants.PRETTY_INDENT not in stdout.getvalue()


def test_log_json_pretty_indent(stdout, service_name, monkeypatch):
# GIVEN a logger with default settings and WHEN POWERTOOLS_DEV=="true"
monkeypatch.setenv(name="POWERTOOLS_DEV", value="true")
logger = Logger(service=service_name, stream=stdout)
logger.info("Test message")
# THEN the json should contain indentation (of constant.PRETTY_INDENT blank spaces)
assert " " * constants.PRETTY_INDENT in stdout.getvalue()