Skip to content

Commit 902f8c3

Browse files
author
Michael Brewer
committed
feat(logger): add option to remove correlation_id
Call remove_keys when the correlation_id is set to None
1 parent 43b828e commit 902f8c3

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

aws_lambda_powertools/logging/logger.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -387,15 +387,18 @@ def structure_logs(self, append: bool = False, **keys):
387387
formatter = self.logger_formatter or LambdaPowertoolsFormatter(**log_keys)
388388
self.registered_handler.setFormatter(formatter)
389389

390-
def set_correlation_id(self, value: str):
390+
def set_correlation_id(self, value: Optional[str]):
391391
"""Sets the correlation_id in the logging json
392392
393393
Parameters
394394
----------
395-
value : str
396-
Value for the correlation id
395+
value : str, optional
396+
Value for the correlation id. None will remove the correlation_id
397397
"""
398-
self.append_keys(correlation_id=value)
398+
if value is None:
399+
self.remove_keys(["correlation_id"])
400+
else:
401+
self.append_keys(correlation_id=value)
399402

400403
@staticmethod
401404
def _get_log_level(level: Union[str, int, None]) -> Union[str, int]:

tests/functional/test_logger.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,20 @@ def handler(event, _):
460460
assert request_id == log["correlation_id"]
461461

462462

463+
def test_logger_set_correlation_id_to_none(lambda_context, stdout, service_name):
464+
# GIVEN a logger with a correlation_id set
465+
logger = Logger(service=service_name, stream=stdout)
466+
logger.set_correlation_id("foo")
467+
468+
# WHEN calling set_correlation_id with None
469+
logger.set_correlation_id(None)
470+
471+
# THEN there should be no correlation_id
472+
logger.info("Foo")
473+
log = capture_logging_output(stdout)
474+
assert "correlation_id" not in log
475+
476+
463477
def test_logger_set_correlation_id_path(lambda_context, stdout, service_name):
464478
# GIVEN
465479
logger = Logger(service=service_name, stream=stdout)

0 commit comments

Comments
 (0)