Skip to content

fix(logger): caplog working with parent Logger #6847

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

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions aws_lambda_powertools/logging/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,9 @@ def _init_logger(
if not self._is_deduplication_disabled:
logger.debug("Adding filter in root logger to suppress child logger records to bubble up")
for handler in logging.root.handlers:
# skip suppressing pytest's handler, allowing caplog fixture usage
if type(handler).__name__ == "LogCaptureHandler" and type(handler).__module__ == "_pytest.logging":
continue
# It'll add a filter to suppress any child logger from self.service
# Example: `Logger(service="order")`, where service is Order
# It'll reject all loggers starting with `order` e.g. order.checkout, order.shared
Expand Down
22 changes: 22 additions & 0 deletions tests/functional/logger/required_dependencies/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from typing import TYPE_CHECKING, Any

import pytest
from _pytest.logging import LogCaptureHandler

from aws_lambda_powertools import Logger
from aws_lambda_powertools.logging import correlation_paths
Expand Down Expand Up @@ -1556,3 +1557,24 @@ def handler(event, context):
# THEN we must be able to inject context
log = capture_logging_output(stdout)
assert request_id == log["correlation_id"]


def test_non_preconfigured_logger_with_caplog(caplog, service_name):
caplog.set_level("INFO")
logger = Logger(service=service_name)
logger.info("testing, testing...")
pytest_handler_existence = any(isinstance(item, LogCaptureHandler) for item in logger._logger.root.handlers)

assert pytest_handler_existence is True
assert len(caplog.records) == 1
assert caplog.records[0].message == "testing, testing..."


def test_child_logger_with_caplog(caplog):
caplog.set_level("INFO")
logger = Logger(child=True)
logger.info("testing, testing...")
pytest_handler_existence = any(isinstance(item, LogCaptureHandler) for item in logger._logger.root.handlers)

assert len(caplog.records) == 1
assert pytest_handler_existence is True
Loading