Skip to content

Commit

Permalink
feat(logger): add get_correlation_id method (#516)
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Brewer authored Jul 19, 2021
1 parent 89e8151 commit f6a5b2a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
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

0 comments on commit f6a5b2a

Please sign in to comment.