Skip to content

Commit 2e4e521

Browse files
author
Michael Brewer
committed
feat(logger): Add set_correlation_id
1 parent 4bee95b commit 2e4e521

File tree

3 files changed

+56
-20
lines changed

3 files changed

+56
-20
lines changed

aws_lambda_powertools/logging/logger.py

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
import sys
77
from typing import Any, Callable, Dict, Optional, Union
88

9-
import jmespath
10-
119
from ..shared import constants
1210
from ..shared.functions import resolve_env_var_choice, resolve_truthy_env_var_choice
1311
from .exceptions import InvalidLoggerSamplingRateError
@@ -227,12 +225,7 @@ def _configure_sampling(self):
227225
f"Please review POWERTOOLS_LOGGER_SAMPLE_RATE environment variable."
228226
)
229227

230-
def inject_lambda_context(
231-
self,
232-
lambda_handler: Callable[[Dict, Any], Any] = None,
233-
log_event: bool = None,
234-
correlation_id_path: Union[str, int] = None,
235-
):
228+
def inject_lambda_context(self, lambda_handler: Callable[[Dict, Any], Any] = None, log_event: bool = None):
236229
"""Decorator to capture Lambda contextual info and inject into logger
237230
238231
Parameters
@@ -241,8 +234,6 @@ def inject_lambda_context(
241234
Method to inject the lambda context
242235
log_event : bool, optional
243236
Instructs logger to log Lambda Event, by default False
244-
correlation_id_path: str, optional
245-
JMESPath expression to find the correlation_id
246237
247238
Environment variables
248239
---------------------
@@ -281,24 +272,18 @@ def handler(event, context):
281272
# Return a partial function with args filled
282273
if lambda_handler is None:
283274
logger.debug("Decorator called with parameters")
284-
return functools.partial(
285-
self.inject_lambda_context, log_event=log_event, correlation_id_path=correlation_id_path
286-
)
275+
return functools.partial(self.inject_lambda_context, log_event=log_event)
287276

288277
log_event = resolve_truthy_env_var_choice(
289278
choice=log_event, env=os.getenv(constants.LOGGER_LOG_EVENT_ENV, "false")
290279
)
291-
correlation_id_path = _get_correlation_id_path(correlation_id_path)
292280

293281
@functools.wraps(lambda_handler)
294282
def decorate(event, context):
295283
lambda_context = build_lambda_context_model(context)
296284
cold_start = _is_cold_start()
297285
self.structure_logs(append=True, cold_start=cold_start, **lambda_context.__dict__)
298286

299-
if correlation_id_path:
300-
self.structure_logs(append=True, correlation_id=jmespath.search(correlation_id_path, event))
301-
302287
if log_event:
303288
logger.debug("Event received")
304289
self.info(event)
@@ -332,6 +317,16 @@ def structure_logs(self, append: bool = False, **kwargs):
332317
# Set a new formatter for a logger handler
333318
handler.setFormatter(JsonFormatter(**self._default_log_keys, **kwargs))
334319

320+
def set_correlation_id(self, value: str):
321+
"""Sets the correlation_id in the logging json
322+
323+
Parameters
324+
----------
325+
value : str
326+
Value for the correlation id
327+
"""
328+
self.structure_logs(append=True, correlation_id=value)
329+
335330
@staticmethod
336331
def _get_log_level(level: Union[str, int]) -> Union[str, int]:
337332
""" Returns preferred log level set by the customer in upper case """

docs/core/logger.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,47 @@ You can append your own keys to your existing Logger via `structure_logs(append=
188188

189189
This example will add `order_id` if its value is not empty, and in subsequent invocations where `order_id` might not be present it'll remove it from the logger.
190190

191+
#### set_correlation_id method
192+
193+
You can set a correlation_id to your existing Logger via `set_correlation_id(value)` method.
194+
195+
=== "collect.py"
196+
197+
```python hl_lines="8"
198+
from aws_lambda_powertools import Logger
199+
from aws_lambda_powertools.utilities.data_classes import APIGatewayProxyEvent
200+
201+
logger = Logger()
202+
203+
def handler(event, context):
204+
event = APIGatewayProxyEvent(event)
205+
logger.set_correlation_id(event.request_context.request_id)
206+
logger.info("Collecting payment")
207+
...
208+
```
209+
=== "Example Event"
210+
211+
```json hl_lines="3"
212+
{
213+
"requestContext": {
214+
"requestId": "correlation_id_value"
215+
}
216+
}
217+
```
218+
=== "Example CloudWatch Logs excerpt"
219+
220+
```json hl_lines="7"
221+
{
222+
"timestamp": "2020-05-24 18:17:33,774",
223+
"level": "INFO",
224+
"location": "collect.handler:1",
225+
"service": "payment",
226+
"sampling_rate": 0.0,
227+
"correlation_id": "correlation_id_value",
228+
"message": "Collecting payment"
229+
}
230+
```
231+
191232
#### extra parameter
192233

193234
Extra parameter is available for all log levels' methods, as implemented in the standard logging library - e.g. `logger.info, logger.warning`.

tests/functional/test_logger.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -442,11 +442,11 @@ def test_logger_exception_extract_exception_name(stdout, service_name):
442442
def test_logger_correlation_id(lambda_context, stdout, service_name):
443443
# GIVEN
444444
logger = Logger(service=service_name, stream=stdout)
445-
request_id = "xxx"
445+
request_id = "xxx-111-222"
446446
mock_event = {"requestContext": {"requestId": request_id}}
447447

448-
@logger.inject_lambda_context(correlation_id_path="requestContext.requestId")
449-
def handler(_1, _2):
448+
def handler(event, _):
449+
logger.set_correlation_id(event["requestContext"]["requestId"])
450450
logger.info("Foo")
451451

452452
# WHEN

0 commit comments

Comments
 (0)