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 all commits
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
16 changes: 13 additions & 3 deletions aws_lambda_powertools/logging/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,16 +387,26 @@ def structure_logs(self, append: bool = False, **keys):
formatter = self.logger_formatter or LambdaPowertoolsFormatter(**log_keys) # type: ignore
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)

def get_correlation_id(self) -> Optional[str]:
"""Gets the correlation_id in the logging json

Returns
-------
str, optional
Value for the correlation id
"""
return self.registered_formatter.log_format.get("correlation_id")

@staticmethod
def _get_log_level(level: Union[str, int, None]) -> Union[str, int]:
"""Returns preferred log level set by the customer in upper case"""
Expand Down
12 changes: 12 additions & 0 deletions tests/functional/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,18 @@ def handler(event, _):
assert request_id == log["correlation_id"]


def test_logger_get_correlation_id(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 get_correlation_id
correlation_id = logger.get_correlation_id()

# THEN it should return the correlation_id
assert "foo" == correlation_id


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