66import sys
77from typing import Any , Callable , Dict , Union
88
9+ import jmespath
10+
911from ..shared import constants
1012from ..shared .functions import resolve_env_var_choice , resolve_truthy_env_var_choice
1113from .exceptions import InvalidLoggerSamplingRateError
@@ -204,7 +206,9 @@ def _configure_sampling(self):
204206 f"Please review POWERTOOLS_LOGGER_SAMPLE_RATE environment variable."
205207 )
206208
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+ ):
208212 """Decorator to capture Lambda contextual info and inject into logger
209213
210214 Parameters
@@ -213,6 +217,8 @@ def inject_lambda_context(self, lambda_handler: Callable[[Dict, Any], Any] = Non
213217 Method to inject the lambda context
214218 log_event : bool, optional
215219 Instructs logger to log Lambda Event, by default False
220+ correlation_id_path: str, optional
221+ Optional JMESPath for the correlation_id
216222
217223 Environment variables
218224 ---------------------
@@ -251,7 +257,9 @@ def handler(event, context):
251257 # Return a partial function with args filled
252258 if lambda_handler is None :
253259 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+ )
255263
256264 log_event = resolve_truthy_env_var_choice (
257265 choice = log_event , env = os .getenv (constants .LOGGER_LOG_EVENT_ENV , "false" )
@@ -263,6 +271,9 @@ def decorate(event, context):
263271 cold_start = _is_cold_start ()
264272 self .structure_logs (append = True , cold_start = cold_start , ** lambda_context .__dict__ )
265273
274+ if correlation_id_path :
275+ self .set_correlation_id (jmespath .search (correlation_id_path , event ))
276+
266277 if log_event :
267278 logger .debug ("Event received" )
268279 self .info (event )
0 commit comments