Skip to content

Commit 3ea4fbb

Browse files
committed
improv: add log filter in root handler to prevent child log records duplication
1 parent e545820 commit 3ea4fbb

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed
+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import logging
2+
3+
4+
class SuppressFilter(logging.Filter):
5+
def __init__(self, logger):
6+
self.logger = logger
7+
8+
def filter(self, record): # noqa: A003
9+
"""Suppress Log Records from registered logger"""
10+
if self.logger in record.name:
11+
return False
12+
return True

aws_lambda_powertools/logging/logger.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from typing import Any, Callable, Dict, Union
99

1010
from .exceptions import InvalidLoggerSamplingRateError
11+
from .filters import SuppressFilter
1112
from .formatter import JsonFormatter
1213
from .lambda_context import build_lambda_context_model
1314

@@ -147,13 +148,6 @@ def _get_logger(self):
147148
def _init_logger(self, **kwargs):
148149
"""Configures new logger"""
149150

150-
# Lambda by default configures the root logger handler
151-
# therefore, we need to remove it to prevent messages being logged twice
152-
# when customers use our Logger
153-
logger.debug("Removing Lambda root handler whether it exists")
154-
root_logger = logging.getLogger()
155-
root_logger.handlers.clear()
156-
157151
# Skip configuration if it's a child logger to prevent
158152
# multiple handlers being attached as well as different sampling mechanisms
159153
# and multiple messages from being logged as handlers can be duplicated
@@ -163,6 +157,10 @@ def _init_logger(self, **kwargs):
163157
self._logger.addHandler(self._handler)
164158
self.structure_logs(**kwargs)
165159

160+
logger.debug("Adding filter in root logger to suppress child logger records to bubble up")
161+
for handler in logging.root.handlers:
162+
handler.addFilter(SuppressFilter(self.service))
163+
166164
def _configure_sampling(self):
167165
"""Dynamically set log level based on sampling rate
168166

0 commit comments

Comments
 (0)