You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/core/logger.md
+70-2
Original file line number
Diff line number
Diff line change
@@ -231,8 +231,9 @@ We provide [built-in JMESPath expressions](#built-in-correlation-id-expressions)
231
231
232
232
### Appending additional keys
233
233
234
-
!!! info "Keys might be persisted across invocations"
235
-
Always set additional keys as part of your handler to ensure they have the latest value. Additional keys are kept in memory as part of a Logger instance and might be reused in non-cold start scenarios.
234
+
!!! info "Custom keys are persisted across warm invocations"
235
+
Always set additional keys as part of your handler to ensure they have the latest value, or explicitly clear them with [`clear_state=True`](#clearing-all-state).
236
+
236
237
237
238
You can append additional keys using either mechanism:
238
239
@@ -426,6 +427,73 @@ You can remove any additional key from Logger state using `remove_keys`.
426
427
}
427
428
```
428
429
430
+
#### Clearing all state
431
+
432
+
Logger is commonly initialized in the global scope. Due to [Lambda Execution Context reuse](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-context.html), this means that custom keys can be persisted across invocations. If you want all custom keys to be deleted, you can use `clear_state=True` param in `inject_lambda_context` decorator.
433
+
434
+
!!! info
435
+
This is useful when you add multiple custom keys conditionally, instead of setting a default `None` value if not present. Any key with `None` value is automatically removed by Logger.
436
+
437
+
!!! danger "This can have unintended side effects if you use Layers"
438
+
Lambda Layers code is imported before the Lambda handler.
439
+
440
+
This means that `clear_state=True` will instruct Logger to remove any keys previously added before Lambda handler execution proceeds.
441
+
442
+
You can either avoid running any code as part of Lambda Layers global scope, or override keys with their latest value as part of handler's execution.
443
+
444
+
=== "collect.py"
445
+
446
+
```python hl_lines="5 8"
447
+
from aws_lambda_powertools import Logger
448
+
449
+
logger = Logger(service="payment")
450
+
451
+
@logger.inject_lambda_context(clear_state=True)
452
+
def handler(event, context):
453
+
if event.get("special_key"):
454
+
# Should only be available in the first request log
455
+
# as the second request doesn't contain `special_key`
Use `logger.exception` method to log contextual information about exceptions. Logger will include `exception_name` and `exception` keys to aid troubleshooting and error enumeration.
0 commit comments