Skip to content

Commit 124a19b

Browse files
committed
docs(logger): custom formatter use case completeness
1 parent 7c44ba8 commit 124a19b

File tree

1 file changed

+24
-10
lines changed

1 file changed

+24
-10
lines changed

docs/core/logger.md

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -862,7 +862,10 @@ logger.info("Collecting payment")
862862

863863
By default, Logger uses [LambdaPowertoolsFormatter](#lambdapowertoolsformatter) that persists its custom structure between non-cold start invocations. There could be scenarios where the existing feature set isn't sufficient to your formatting needs.
864864

865-
For **minor changes like remapping keys** after all log record processing has completed, you can override `serialize` method from [LambdaPowertoolsFormatter](#lambdapowertoolsformatter):
865+
???+ info
866+
The most common use cases are remapping keys by bringing your existing schema, and redacting sensitive information you know upfront.
867+
868+
For these, you can override the `serialize` method from [LambdaPowertoolsFormatter](#lambdapowertoolsformatter).
866869

867870
=== "custom_formatter.py"
868871

@@ -892,28 +895,39 @@ For **minor changes like remapping keys** after all log record processing has co
892895
}
893896
```
894897

895-
For **replacing the formatter entirely**, you can subclass `BasePowertoolsFormatter`, implement `append_keys` method, and override `format` standard logging method. This ensures the current feature set of Logger like [injecting Lambda context](#capturing-lambda-context-info) and [sampling](#sampling-debug-logs) will continue to work.
898+
The `log` argument is the final log record containing [our standard keys](#standard-structured-keys), optionally [Lambda context keys](#capturing-lambda-context-info), and any custom key you might have added via [append_keys](#append_keys-method) or the [extra parameter](#extra-parameter).
899+
900+
For exceptional cases where you want to completely replace our formatter logic, you can subclass `BasePowertoolsFormatter`.
901+
902+
???+ warning
903+
You will need to implement `append_keys`, `clear_state`, override `format`, and optionally `remove_keys` to keep the same feature set Powertools Logger provides. This also means keeping state of logging keys added.
896904

897-
???+ info
898-
You might need to implement `remove_keys` method if you make use of the feature too.
899905

900906
=== "collect.py"
901907

902-
```python hl_lines="2 4 7 12 16 27"
908+
```python hl_lines="5 7 9-10 13 17 21 24 35"
909+
import logging
910+
from typing import Iterable, List, Optional
911+
903912
from aws_lambda_powertools import Logger
904913
from aws_lambda_powertools.logging.formatter import BasePowertoolsFormatter
905914

906915
class CustomFormatter(BasePowertoolsFormatter):
907-
custom_format = {} # arbitrary dict to hold our structured keys
916+
def __init__(self, log_record_order: Optional[List[str]], *args, **kwargs):
917+
self.log_record_order = log_record_order or ["level", "location", "message", "timestamp"]
918+
self.log_format = dict.fromkeys(self.log_record_order)
919+
super().__init__(*args, **kwargs)
908920

909921
def append_keys(self, **additional_keys):
910922
# also used by `inject_lambda_context` decorator
911-
self.custom_format.update(additional_keys)
923+
self.log_format.update(additional_keys)
912924

913-
# Optional unless you make use of this Logger feature
914925
def remove_keys(self, keys: Iterable[str]):
915926
for key in keys:
916-
self.custom_format.pop(key, None)
927+
self.log_format.pop(key, None)
928+
929+
def clear_state(self):
930+
self.log_format = dict.fromkeys(self.log_record_order)
917931

918932
def format(self, record: logging.LogRecord) -> str: # noqa: A003
919933
"""Format logging record as structured JSON str"""
@@ -922,7 +936,7 @@ For **replacing the formatter entirely**, you can subclass `BasePowertoolsFormat
922936
"event": super().format(record),
923937
"timestamp": self.formatTime(record),
924938
"my_default_key": "test",
925-
**self.custom_format,
939+
**self.log_format,
926940
}
927941
)
928942

0 commit comments

Comments
 (0)