Skip to content

Commit 5354701

Browse files
committed
docs: bring your own JSON serializer feat
1 parent 91affa4 commit 5354701

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

aws_lambda_powertools/logging/formatter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,8 @@ class LambdaPowertoolsFormatter(BasePowertoolsFormatter):
5757

5858
def __init__(
5959
self,
60-
json_serializer: Optional[Callable[[Any], Any]] = None,
61-
json_deserializer: Optional[Callable[[Any], Any]] = None,
60+
json_serializer: Optional[Callable[[Dict], str]] = None,
61+
json_deserializer: Optional[Callable[[Dict], str]] = None,
6262
json_default: Optional[Callable[[Any], Any]] = None,
6363
datefmt: str = None,
6464
log_record_order: List[str] = None,

docs/core/logger.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -801,6 +801,31 @@ For this, you can subclass `BasePowertoolsFormatter`, implement `append_keys` me
801801
}
802802
```
803803

804+
#### Bring your own JSON serializer
805+
806+
By default, Logger uses `json.dumps` and `json.loads` as serializer and deserializer respectively. There could be scenarios where you are making use of alternative JSON libraries like [orjson](https://github.com/ijl/orjson).
807+
808+
As parameters don't always translate well between them, you can pass any callable that receives a `Dict` and return a `str`:
809+
810+
=== "collect.py"
811+
812+
```python hl_lines="1 5-6 9-10"
813+
import orjson
814+
815+
from aws_lambda_powertools import Logger
816+
817+
custom_serializer = orjson.dumps
818+
custom_deserializer = orjson.loads
819+
820+
logger = Logger(service="payment",
821+
json_serializer=custom_serializer,
822+
json_deserializer=custom_deserializer
823+
)
824+
825+
# when using parameters, you can pass a partial
826+
# custom_serializer=functools.partial(orjson.dumps, option=orjson.OPT_SERIALIZE_NUMPY)
827+
```
828+
804829
## Built-in Correlation ID expressions
805830

806831
You can use any of the following built-in JMESPath expressions as part of [inject_lambda_context decorator](#setting-a-correlation-id).

0 commit comments

Comments
 (0)