Skip to content

Commit

Permalink
feat(logger): add removeFilter
Browse files Browse the repository at this point in the history
  • Loading branch information
heitorlessa committed Nov 21, 2023
1 parent 2e1dfb6 commit 0d227b7
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
5 changes: 4 additions & 1 deletion aws_lambda_powertools/logging/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def _is_cold_start() -> bool:
return cold_start


class Logger(logging.Logger):
class Logger:
"""Creates and setups a logger to format statements in JSON.
Includes service name and any additional key=value into logs
Expand Down Expand Up @@ -686,6 +686,9 @@ def addHandler(self, handler: logging.Handler) -> None:
def addFilter(self, filter: logging._FilterType) -> None: # noqa: A002 # filter built-in usage
return self._logger.addFilter(filter)

def removeFilter(self, filter: logging._FilterType) -> None: # noqa: A002 # filter built-in usage
return self._logger.removeFilter(filter)

@property
def registered_handler(self) -> logging.Handler:
"""Convenience property to access the first logger handler"""
Expand Down
17 changes: 11 additions & 6 deletions tests/functional/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -1079,21 +1079,26 @@ def test_log_level_advanced_logging_controler_warning_different_log_levels_using
assert logger.log_level == logging.INFO


def test_logger_add_filter(stdout, service_name):
def test_logger_add_remove_filter(stdout, service_name):
# GIVEN a Logger with a custom logging filter
class MyFilter(logging.Filter):
class ApiKeyFilter(logging.Filter):
def filter(self, record):
if getattr(record, "api_key", None):
record.api_key = "REDACTED"

return True

redact_api_key_filter = ApiKeyFilter()
logger = Logger(service=service_name, stream=stdout)
logger.addFilter(MyFilter())
logger.addFilter(redact_api_key_filter)

# WHEN a new log statement is issued
logger.info("log", api_key=secrets.token_urlsafe())
# AND another log statement is issued after filter is removed
logger.info("filtered", api_key=secrets.token_urlsafe())
logger.removeFilter(redact_api_key_filter)
logger.info("unfiltered", api_key=secrets.token_urlsafe())

# THEN logging filter should be called and mutate the log record accordingly
log = capture_logging_output(stdout)
assert log["api_key"] == "REDACTED"
log = capture_multiple_logging_statements_output(stdout)
assert log[0]["api_key"] == "REDACTED"
assert log[1]["api_key"] != "REDACTED"

0 comments on commit 0d227b7

Please sign in to comment.