Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(logger): add get_correlation_id method #516

Merged
merged 7 commits into from
Jul 19, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions aws_lambda_powertools/logging/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,15 +387,18 @@ def structure_logs(self, append: bool = False, **keys):
formatter = self.logger_formatter or LambdaPowertoolsFormatter(**log_keys)
self.registered_handler.setFormatter(formatter)

def set_correlation_id(self, value: str):
def set_correlation_id(self, value: Optional[str]):
"""Sets the correlation_id in the logging json

Parameters
----------
value : str
Value for the correlation id
value : str, optional
Value for the correlation id. None will remove the correlation_id
"""
self.append_keys(correlation_id=value)
if value is None:
self.remove_keys(["correlation_id"])
else:
self.append_keys(correlation_id=value)

@staticmethod
def _get_log_level(level: Union[str, int, None]) -> Union[str, int]:
Expand Down
14 changes: 14 additions & 0 deletions tests/functional/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,20 @@ def handler(event, _):
assert request_id == log["correlation_id"]


def test_logger_set_correlation_id_to_none(lambda_context, stdout, service_name):
# GIVEN a logger with a correlation_id set
logger = Logger(service=service_name, stream=stdout)
logger.set_correlation_id("foo")

# WHEN calling set_correlation_id with None
logger.set_correlation_id(None)

# THEN there should be no correlation_id
logger.info("Foo")
log = capture_logging_output(stdout)
assert "correlation_id" not in log


def test_logger_set_correlation_id_path(lambda_context, stdout, service_name):
# GIVEN
logger = Logger(service=service_name, stream=stdout)
Expand Down