From 85da9966d11ec195d9c95deaa126b62439dab7de Mon Sep 17 00:00:00 2001 From: Atul Joshi <120785343+AtulJoshi1206@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:05:25 +0530 Subject: [PATCH] fix(logger): child Logger without a level follows its parent level again Since #5950 a child Logger always called setLevel(), so without an explicit level it resolved to INFO (or the env var) and stopped inheriting the parent's level. DEBUG logs from child modules were lost when the parent used DEBUG, setLevel() or sampling, and INFO logs leaked when the parent used WARNING. A child now only sets a level when one is passed, and otherwise stays NOTSET like before 3.6.0. The same applies to refresh_sample_rate_calculation(), which used to pin a child to INFO on warm invocations. log_level returns the effective level, so a child reports, and copy_config_to_registered_loggers copies, the level the child actually logs at. Explicit child levels (#5950) and the ALC > explicit level > env var priority are unchanged. --- aws_lambda_powertools/logging/logger.py | 12 +- docs/core/logger.md | 2 + .../required_dependencies/test_logger.py | 112 ++++++++++++++++++ .../test_logger_utils.py | 14 +++ 4 files changed, 136 insertions(+), 4 deletions(-) diff --git a/aws_lambda_powertools/logging/logger.py b/aws_lambda_powertools/logging/logger.py index 5d2a515d516..e99b9974e1b 100644 --- a/aws_lambda_powertools/logging/logger.py +++ b/aws_lambda_powertools/logging/logger.py @@ -107,7 +107,7 @@ class Logger: level : str, int optional The level to set. Can be a string representing the level name: 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' or an integer representing the level value: 10 for 'DEBUG', 20 for 'INFO', 30 for 'WARNING', 40 for 'ERROR', 50 for 'CRITICAL'. - by default "INFO" + by default "INFO"; a child Logger without a level follows its parent's level child: bool, optional create a child Logger named ., False by default sampling_rate: float, optional @@ -283,7 +283,8 @@ def __init__( self._buffer_cache = LoggerBufferCache(max_size_bytes=self._buffer_config.max_bytes) # Used in case of sampling - self.initial_log_level = self._determine_log_level(level) + # A child Logger without an explicit level stays NOTSET, so it follows its parent's level + self.initial_log_level = logging.NOTSET if child and level is None else self._determine_log_level(level) self._init_logger( formatter_options=formatter_options, @@ -348,7 +349,9 @@ def _init_logger( # c) multiple messages from being logged as handlers can be duplicated is_logger_preconfigured = getattr(self._logger, LOGGER_ATTRIBUTE_PRECONFIGURED, False) if self.child: - self.setLevel(log_level) + # Only set a level when one was given; otherwise the child follows its parent's level + if log_level is not None: + self.setLevel(log_level) if getattr(self._logger.parent, "powertools_buffer_config", None): # Initializes a new, empty LoggerBufferCache for child logger # Preserves parent's buffer configuration while resetting cache contents @@ -973,7 +976,8 @@ def registered_formatter(self) -> BasePowertoolsFormatter: @property def log_level(self) -> int: - return self._logger.level + # Effective level, so a child Logger without its own level reports the level it inherits + return self._logger.getEffectiveLevel() @property def name(self) -> str: diff --git a/docs/core/logger.md b/docs/core/logger.md index 1f60b9ff124..9de9d94d991 100644 --- a/docs/core/logger.md +++ b/docs/core/logger.md @@ -964,6 +964,8 @@ For inheritance, Logger uses `child` parameter to ensure we don't compete with i Changes are bidirectional between parents and loggers. That is, appending a key in a child or parent will ensure both have them. This means, having the same `service` name is important when instantiating them. +A child Logger without a `level` follows its parent's log level, including later changes from `setLevel()` and sampling. Pass `level` to give a child its own log level. + === "logging_inheritance_good.py" ```python hl_lines="1 9" diff --git a/tests/functional/logger/required_dependencies/test_logger.py b/tests/functional/logger/required_dependencies/test_logger.py index afc16b6cbfb..f00de41e1a3 100644 --- a/tests/functional/logger/required_dependencies/test_logger.py +++ b/tests/functional/logger/required_dependencies/test_logger.py @@ -10,6 +10,7 @@ import secrets import string import sys +import warnings from collections import namedtuple from datetime import datetime, timezone from typing import TYPE_CHECKING, Any @@ -1447,6 +1448,117 @@ def test_logger_change_level_child_logger(stdout, service_name): assert "service" in logs[0] +def test_child_logger_without_level_follows_parent_level(stdout, service_name): + # GIVEN a child Logger without a level, created before its parent as when imported from another module + child_logger = Logger(service=service_name, child=True, stream=stdout) + Logger(service=service_name, stream=stdout, level="DEBUG") + + # WHEN the child emits a DEBUG log + child_logger.debug("CHILD") + + # THEN the child must follow the parent's DEBUG level + log = capture_logging_output(stdout) + assert log["message"] == "CHILD" + assert log["level"] == "DEBUG" + assert child_logger.log_level == logging.DEBUG + + +def test_child_logger_without_level_follows_parent_set_level(stdout, service_name): + # GIVEN a parent Logger and a child Logger without a level + logger = Logger(service=service_name, stream=stdout) + child_logger = Logger(service=service_name, child=True, stream=stdout) + + # WHEN the parent switches to DEBUG after the child was created + logger.setLevel("DEBUG") + child_logger.debug("CHILD") + + # THEN the child must follow the new parent level + log = capture_logging_output(stdout) + assert log["message"] == "CHILD" + + +def test_child_logger_without_level_follows_less_verbose_parent_level(stdout, service_name): + # GIVEN a parent Logger with WARNING level and a child Logger without a level + Logger(service=service_name, stream=stdout, level="WARNING") + child_logger = Logger(service=service_name, child=True, stream=stdout) + + # WHEN the child emits an INFO log + child_logger.info("CHILD") + + # THEN nothing must be emitted, as the parent level is WARNING + assert stdout.getvalue() == "" + + +def test_child_logger_without_level_follows_parent_sampled_debug_level(stdout, service_name): + # GIVEN a parent Logger sampling every request at DEBUG level and a child Logger without a level + Logger(service=service_name, stream=stdout, sampling_rate=1) + child_logger = Logger(service=service_name, child=True, stream=stdout) + + # WHEN the child emits a DEBUG log + child_logger.debug("CHILD") + + # THEN the child must follow the sampled DEBUG level + log = capture_logging_output(stdout) + assert log["message"] == "CHILD" + + +def test_child_logger_without_level_follows_parent_level_after_sample_rate_refresh( + monkeypatch, + lambda_context, + stdout, + service_name, +): + # GIVEN sampling is configured for the function but this request isn't sampled + monkeypatch.setenv(constants.LOGGER_LOG_SAMPLING_RATE, "0") + # GIVEN a parent Logger with DEBUG level and a child Logger without a level decorating the handler + Logger(service=service_name, stream=stdout, level="DEBUG") + child_logger = Logger(service=service_name, child=True, stream=stdout) + + @child_logger.inject_lambda_context + def handler(event, context): + child_logger.debug("CHILD") + + # WHEN the handler is invoked twice, refreshing the sampling decision on the warm invocation + handler({}, lambda_context) + handler({}, lambda_context) + + # THEN the child must keep following the parent's DEBUG level on every invocation + logs = capture_multiple_logging_statements_output(stdout) + assert [log["message"] for log in logs] == ["CHILD", "CHILD"] + + +def test_child_logger_without_level_follows_parent_level_over_env_var(monkeypatch, stdout, service_name): + # GIVEN POWERTOOLS_LOG_LEVEL is DEBUG but the parent Logger has an explicit INFO level + monkeypatch.setenv(constants.POWERTOOLS_LOG_LEVEL_ENV, "DEBUG") + Logger(service=service_name, stream=stdout, level="INFO") + child_logger = Logger(service=service_name, child=True, stream=stdout) + + # WHEN the child emits a DEBUG log + child_logger.debug("CHILD") + + # THEN nothing must be emitted, as an explicit level takes precedence over POWERTOOLS_LOG_LEVEL + assert stdout.getvalue() == "" + + +@pytest.mark.parametrize("child_level", [None, "DEBUG"]) +def test_child_logger_respects_advanced_logging_controls(monkeypatch, stdout, service_name, child_level): + # GIVEN AWS Lambda Advanced Logging Controls is set to INFO + monkeypatch.setenv(constants.LAMBDA_LOG_LEVEL_ENV, "INFO") + Logger(service=service_name, stream=stdout) + + # WHEN a child Logger is created with or without a DEBUG level + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + child_logger = Logger(service=service_name, child=True, stream=stdout, level=child_level) + child_logger.debug("CHILD DEBUG") + child_logger.info("CHILD INFO") + + # THEN ALC level must take precedence for the child + logs = capture_multiple_logging_statements_output(stdout) + assert [log["message"] for log in logs] == ["CHILD INFO"] + assert child_logger.log_level == logging.INFO + + def test_clear_state_with_append_keys(): # GIVEN a Logger is initialized logger = Logger(service="service_name", stream=stdout) diff --git a/tests/functional/logger/required_dependencies/test_logger_utils.py b/tests/functional/logger/required_dependencies/test_logger_utils.py index 24a082729df..b0357a7bb36 100644 --- a/tests/functional/logger/required_dependencies/test_logger_utils.py +++ b/tests/functional/logger/required_dependencies/test_logger_utils.py @@ -252,6 +252,20 @@ def test_copy_config_to_parent_loggers_only_with_exclude(stdout): assert child.parent.name == service +def test_copy_config_from_child_logger_uses_parent_level(stdout, logger): + # GIVEN an external logger, a parent Logger with DEBUG level and a child Logger without a level + ext_logger = logger() + service = service_name() + Logger(stream=stdout, service=service, level="DEBUG") + child = Logger(stream=stdout, service=service, child=True) + + # WHEN configuration is copied from the child Logger + utils.copy_config_to_registered_loggers(source_logger=child, include={ext_logger.name}) + + # THEN the external logger must use the level the child logs at, inherited from its parent + assert ext_logger.level == logging.DEBUG + + def test_copy_config_to_ext_loggers_no_duplicate_logs(stdout, logger, log_level): # GIVEN an root logger, external logger and Powertools for AWS Lambda (Python) logger initialized