|
7 | 7 | import time
|
8 | 8 | import traceback
|
9 | 9 | from abc import ABCMeta, abstractmethod
|
| 10 | +from contextlib import contextmanager |
10 | 11 | from contextvars import ContextVar
|
11 | 12 | from datetime import datetime, timezone
|
12 | 13 | from functools import partial
|
13 |
| -from typing import TYPE_CHECKING, Any, Callable, Iterable |
| 14 | +from typing import TYPE_CHECKING, Any, Callable, Generator, Iterable |
14 | 15 |
|
15 | 16 | from aws_lambda_powertools.shared import constants
|
16 | 17 | from aws_lambda_powertools.shared.functions import powertools_dev_is_set
|
@@ -62,6 +63,10 @@ def clear_state(self) -> None:
|
62 | 63 | """Removes any previously added logging keys"""
|
63 | 64 | raise NotImplementedError()
|
64 | 65 |
|
| 66 | + @contextmanager |
| 67 | + def append_context_keys(self, **additional_keys: Any) -> Generator[None, None, None]: |
| 68 | + yield |
| 69 | + |
65 | 70 | # These specific thread-safe methods are necessary to manage shared context in concurrent environments.
|
66 | 71 | # They prevent race conditions and ensure data consistency across multiple threads.
|
67 | 72 | def thread_safe_append_keys(self, **additional_keys) -> None:
|
@@ -263,6 +268,31 @@ def clear_state(self) -> None:
|
263 | 268 | self.log_format = dict.fromkeys(self.log_record_order)
|
264 | 269 | self.log_format.update(**self.keys_combined)
|
265 | 270 |
|
| 271 | + @contextmanager |
| 272 | + def append_context_keys(self, **additional_keys: Any) -> Generator[None, None, None]: |
| 273 | + """ |
| 274 | + Context manager to temporarily add logging keys. |
| 275 | +
|
| 276 | + Parameters: |
| 277 | + ----------- |
| 278 | + **keys: Any |
| 279 | + Key-value pairs to include in the log context during the lifespan of the context manager. |
| 280 | +
|
| 281 | + Example: |
| 282 | + -------- |
| 283 | + >>> logger = Logger(service="example_service") |
| 284 | + >>> with logger.append_context_keys(user_id="123", operation="process"): |
| 285 | + >>> logger.info("Log with context") |
| 286 | + >>> logger.info("Log without context") |
| 287 | + """ |
| 288 | + # Add keys to the context |
| 289 | + self.append_keys(**additional_keys) |
| 290 | + try: |
| 291 | + yield |
| 292 | + finally: |
| 293 | + # Remove the keys after exiting the context |
| 294 | + self.remove_keys(additional_keys.keys()) |
| 295 | + |
266 | 296 | # These specific thread-safe methods are necessary to manage shared context in concurrent environments.
|
267 | 297 | # They prevent race conditions and ensure data consistency across multiple threads.
|
268 | 298 | def thread_safe_append_keys(self, **additional_keys) -> None:
|
|
0 commit comments