6
6
import sys
7
7
from typing import Any , Callable , Dict , Union
8
8
9
+ import jmespath
10
+
9
11
from ..shared import constants
10
12
from ..shared .functions import resolve_env_var_choice , resolve_truthy_env_var_choice
11
13
from .exceptions import InvalidLoggerSamplingRateError
@@ -204,7 +206,9 @@ def _configure_sampling(self):
204
206
f"Please review POWERTOOLS_LOGGER_SAMPLE_RATE environment variable."
205
207
)
206
208
207
- def inject_lambda_context (self , lambda_handler : Callable [[Dict , Any ], Any ] = None , log_event : bool = None ):
209
+ def inject_lambda_context (
210
+ self , lambda_handler : Callable [[Dict , Any ], Any ] = None , log_event : bool = None , correlation_id_path : str = None
211
+ ):
208
212
"""Decorator to capture Lambda contextual info and inject into logger
209
213
210
214
Parameters
@@ -213,6 +217,8 @@ def inject_lambda_context(self, lambda_handler: Callable[[Dict, Any], Any] = Non
213
217
Method to inject the lambda context
214
218
log_event : bool, optional
215
219
Instructs logger to log Lambda Event, by default False
220
+ correlation_id_path: str, optional
221
+ Optional JMESPath for the correlation_id
216
222
217
223
Environment variables
218
224
---------------------
@@ -251,7 +257,9 @@ def handler(event, context):
251
257
# Return a partial function with args filled
252
258
if lambda_handler is None :
253
259
logger .debug ("Decorator called with parameters" )
254
- return functools .partial (self .inject_lambda_context , log_event = log_event )
260
+ return functools .partial (
261
+ self .inject_lambda_context , log_event = log_event , correlation_id_path = correlation_id_path
262
+ )
255
263
256
264
log_event = resolve_truthy_env_var_choice (
257
265
choice = log_event , env = os .getenv (constants .LOGGER_LOG_EVENT_ENV , "false" )
@@ -263,6 +271,9 @@ def decorate(event, context):
263
271
cold_start = _is_cold_start ()
264
272
self .structure_logs (append = True , cold_start = cold_start , ** lambda_context .__dict__ )
265
273
274
+ if correlation_id_path :
275
+ self .set_correlation_id (jmespath .search (correlation_id_path , event ))
276
+
266
277
if log_event :
267
278
logger .debug ("Event received" )
268
279
self .info (event )
0 commit comments