Skip to content

Commit a0ef408

Browse files
feat(logger): pretty-print JSON when POWERTOOLS_DEV is set (#1548)
Co-authored-by: Heitor Lessa <[email protected]>
1 parent 22459e7 commit a0ef408

File tree

4 files changed

+36
-1
lines changed

4 files changed

+36
-1
lines changed

aws_lambda_powertools/logging/formatter.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
1010

1111
from ..shared import constants
12+
from ..shared.functions import strtobool
1213

1314
RESERVED_LOG_ATTRS = (
1415
"name",
@@ -111,9 +112,15 @@ def __init__(
111112
Key-value to be included in log messages
112113
113114
"""
115+
114116
self.json_deserializer = json_deserializer or json.loads
115117
self.json_default = json_default or str
116-
self.json_serializer = json_serializer or partial(json.dumps, default=self.json_default, separators=(",", ":"))
118+
self.json_indent = (
119+
constants.PRETTY_INDENT if strtobool(os.getenv("POWERTOOLS_DEV", "0")) else constants.COMPACT_INDENT
120+
) # indented json serialization when in AWS SAM Local
121+
self.json_serializer = json_serializer or partial(
122+
json.dumps, default=self.json_default, separators=(",", ":"), indent=self.json_indent
123+
)
117124

118125
self.datefmt = datefmt
119126
self.use_datetime_directive = use_datetime_directive

aws_lambda_powertools/shared/constants.py

+4
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,7 @@
3232
"cold_start",
3333
"xray_trace_id",
3434
]
35+
36+
# JSON indentation level
37+
PRETTY_INDENT: int = 4
38+
COMPACT_INDENT = None

docs/core/logger.md

+3
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,9 @@ If you prefer configuring it separately, or you'd want to bring this JSON Format
369369
| **`log_record_order`** | set order of log keys when logging | `["level", "location", "message", "timestamp"]` |
370370
| **`kwargs`** | key-value to be included in log messages | `None` |
371371

372+
???+ info
373+
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.
374+
372375
```python hl_lines="2 7-8" title="Pre-configuring Lambda Powertools Formatter"
373376
--8<-- "examples/logger/src/powertools_formatter_setup.py"
374377
```

tests/functional/test_logger_powertools_formatter.py

+21
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""aws_lambda_logging tests."""
22
import io
33
import json
4+
import os
45
import random
56
import string
67
import time
@@ -288,3 +289,23 @@ def test_log_formatting(stdout, service_name):
288289

289290
# THEN the formatting should be applied (NB. this is valid json, but hasn't be parsed)
290291
assert log_dict["message"] == '["foo bar 123 [1, None]", null]'
292+
293+
294+
def test_log_json_indent_compact_indent(stdout, service_name, monkeypatch):
295+
# GIVEN a logger with default settings and WHEN POWERTOOLS_DEV is not set
296+
monkeypatch.delenv(name="POWERTOOLS_DEV", raising=False)
297+
logger = Logger(service=service_name, stream=stdout)
298+
logger.info("Test message")
299+
# THEN the json should not have multiple lines
300+
new_lines = stdout.getvalue().count(os.linesep)
301+
assert new_lines == 1
302+
303+
304+
def test_log_json_pretty_indent(stdout, service_name, monkeypatch):
305+
# GIVEN a logger with default settings and WHEN POWERTOOLS_DEV=="true"
306+
monkeypatch.setenv(name="POWERTOOLS_DEV", value="true")
307+
logger = Logger(service=service_name, stream=stdout)
308+
logger.info("Test message")
309+
# THEN the json should contain more than line
310+
new_lines = stdout.getvalue().count(os.linesep)
311+
assert new_lines > 1

0 commit comments

Comments
 (0)