Skip to content
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
12 changes: 4 additions & 8 deletions aws_lambda_powertools/logging/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@
extract_event_from_common_models,
get_tracer_id,
is_durable_context,
resolve_bool_env_var,
resolve_env_var_choice,
resolve_truthy_env_var_choice,
)
from aws_lambda_powertools.utilities import jmespath_utils
from aws_lambda_powertools.warnings import PowertoolsUserWarning
Expand Down Expand Up @@ -258,9 +258,7 @@ def __init__(

self.log_uncaught_exceptions = log_uncaught_exceptions

self._is_deduplication_disabled = resolve_truthy_env_var_choice(
env=os.getenv(constants.LOGGER_LOG_DEDUPLICATION_ENV, "false"),
)
self._is_deduplication_disabled = resolve_bool_env_var(constants.LOGGER_LOG_DEDUPLICATION_ENV, default=False)
self._logger = self._get_logger()
self.logger_handler = logger_handler or self._get_handler()

Expand Down Expand Up @@ -517,10 +515,8 @@ def handler(event, context):
flush_buffer_on_uncaught_error=flush_buffer_on_uncaught_error,
)

log_event = resolve_truthy_env_var_choice(
env=os.getenv(constants.LOGGER_LOG_EVENT_ENV, "false"),
choice=log_event,
)
if log_event is None:
log_event = resolve_bool_env_var(constants.LOGGER_LOG_EVENT_ENV, default=False)

@functools.wraps(lambda_handler)
def decorate(event, context, *args, **kwargs):
Expand Down
9 changes: 3 additions & 6 deletions aws_lambda_powertools/middleware_factory/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
import functools
import inspect
import logging
import os
from typing import TYPE_CHECKING, Any

from aws_lambda_powertools.middleware_factory.exceptions import MiddlewareInvalidArgumentError
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import resolve_truthy_env_var_choice
from aws_lambda_powertools.shared.functions import resolve_bool_env_var
from aws_lambda_powertools.tracing import Tracer

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -111,10 +110,8 @@ def lambda_handler(event, context):
if decorator is None:
return functools.partial(lambda_handler_decorator, trace_execution=trace_execution)

trace_execution = resolve_truthy_env_var_choice(
env=os.getenv(constants.MIDDLEWARE_FACTORY_TRACE_ENV, "false"),
choice=trace_execution,
)
if trace_execution is None:
trace_execution = resolve_bool_env_var(constants.MIDDLEWARE_FACTORY_TRACE_ENV, default=False)

@functools.wraps(decorator)
def final_decorator(func: Callable | None = None, **kwargs: Any):
Expand Down
28 changes: 10 additions & 18 deletions aws_lambda_powertools/tracing/tracer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@

from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
resolve_bool_env_var,
resolve_env_var_choice,
resolve_truthy_env_var_choice,
sanitize_xray_segment_name,
)
from aws_lambda_powertools.shared.lazy_import import LazyLoader
Expand Down Expand Up @@ -334,14 +334,10 @@ def handler(event, context):
)

lambda_handler_name = lambda_handler.__name__
capture_response = resolve_truthy_env_var_choice(
env=os.getenv(constants.TRACER_CAPTURE_RESPONSE_ENV, "true"),
choice=capture_response,
)
capture_error = resolve_truthy_env_var_choice(
env=os.getenv(constants.TRACER_CAPTURE_ERROR_ENV, "true"),
choice=capture_error,
)
if capture_response is None:
capture_response = resolve_bool_env_var(constants.TRACER_CAPTURE_RESPONSE_ENV, default=True)
if capture_error is None:
capture_error = resolve_bool_env_var(constants.TRACER_CAPTURE_ERROR_ENV, default=True)

@functools.wraps(lambda_handler)
def decorate(event, context, **kwargs):
Expand Down Expand Up @@ -558,14 +554,10 @@ async def async_tasks():
# Valid characters can be found at http://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html
method_name = sanitize_xray_segment_name(f"{method.__module__}.{method.__qualname__}")

capture_response = resolve_truthy_env_var_choice(
env=os.getenv(constants.TRACER_CAPTURE_RESPONSE_ENV, "true"),
choice=capture_response,
)
capture_error = resolve_truthy_env_var_choice(
env=os.getenv(constants.TRACER_CAPTURE_ERROR_ENV, "true"),
choice=capture_error,
)
if capture_response is None:
capture_response = resolve_bool_env_var(constants.TRACER_CAPTURE_RESPONSE_ENV, default=True)
if capture_error is None:
capture_error = resolve_bool_env_var(constants.TRACER_CAPTURE_ERROR_ENV, default=True)

# Maintenance: Need a factory/builder here to simplify this now
if inspect.iscoroutinefunction(method):
Expand Down Expand Up @@ -804,7 +796,7 @@ def _is_tracer_disabled() -> bool | str:
is_lambda_env = os.getenv(constants.LAMBDA_TASK_ROOT_ENV)
is_lambda_sam_cli = os.getenv(constants.SAM_LOCAL_ENV)
is_chalice_cli = os.getenv(constants.CHALICE_LOCAL_ENV)
is_disabled = resolve_truthy_env_var_choice(env=os.getenv(constants.TRACER_DISABLED_ENV, "false"))
is_disabled = resolve_bool_env_var(constants.TRACER_DISABLED_ENV, default=False)

if is_disabled:
logger.debug("Tracing has been disabled via env var POWERTOOLS_TRACE_DISABLED")
Expand Down
65 changes: 65 additions & 0 deletions tests/functional/logger/required_dependencies/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
)
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.utilities.data_classes import S3Event, event_source
from aws_lambda_powertools.warnings import PowertoolsUserWarning

if TYPE_CHECKING:
from collections.abc import Callable, Iterable
Expand Down Expand Up @@ -323,6 +324,70 @@ def handler(event, context):
assert log["message"] != lambda_event


@pytest.mark.parametrize("value", ["", "true "])
def test_inject_lambda_context_log_event_env_var_unparsable_falls_back_to_default(
monkeypatch,
lambda_context,
stdout,
lambda_event,
service_name,
value,
):
# GIVEN POWERTOOLS_LOGGER_LOG_EVENT has an empty or unparsable value
monkeypatch.setenv("POWERTOOLS_LOGGER_LOG_EVENT", value)
logger = Logger(service=service_name, stream=stdout)

# WHEN a lambda function is decorated with logger
# THEN it should warn naming the variable instead of raising ValueError
with pytest.warns(PowertoolsUserWarning, match="POWERTOOLS_LOGGER_LOG_EVENT"):

@logger.inject_lambda_context
def handler(event, context):
logger.info("Hello")

handler(lambda_event, lambda_context)

# THEN logger should fall back to not logging the event
log = capture_logging_output(stdout)
assert log["message"] == "Hello"


def test_inject_lambda_context_log_event_explicit_choice_ignores_unparsable_env_var(
monkeypatch,
lambda_context,
stdout,
lambda_event,
service_name,
):
# GIVEN POWERTOOLS_LOGGER_LOG_EVENT has an unparsable value
monkeypatch.setenv("POWERTOOLS_LOGGER_LOG_EVENT", "")
logger = Logger(service=service_name, stream=stdout)

# WHEN log_event is passed explicitly
@logger.inject_lambda_context(log_event=True)
def handler(event, context):
logger.info("Hello")

handler(lambda_event, lambda_context)

# THEN the explicit choice should win
logged_event, _ = capture_multiple_logging_statements_output(stdout)
assert logged_event["message"] == lambda_event


def test_logger_log_deduplication_env_var_unparsable_falls_back_to_default(monkeypatch, stdout, service_name):
# GIVEN POWERTOOLS_LOG_DEDUPLICATION_DISABLED has an empty value
monkeypatch.setenv(constants.LOGGER_LOG_DEDUPLICATION_ENV, "")

# WHEN Logger is initialized
# THEN it should warn naming the variable instead of raising ValueError
with pytest.warns(PowertoolsUserWarning, match=constants.LOGGER_LOG_DEDUPLICATION_ENV):
logger = Logger(service=service_name, stream=stdout)

logger.info("Hello")
assert capture_logging_output(stdout)["message"] == "Hello"


def test_inject_lambda_cold_start(lambda_context, stdout, service_name):
# cold_start can be false as it's a global variable in Logger module
# so we reset it to simulate the correct behaviour
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import pytest

from aws_lambda_powertools.middleware_factory import lambda_handler_decorator
from aws_lambda_powertools.warnings import PowertoolsUserWarning


def test_factory_explicit_tracing(monkeypatch):
Expand Down Expand Up @@ -30,3 +33,23 @@ def lambda_handler(evt, ctx):
return True

lambda_handler({}, {})


def test_factory_tracing_env_var_unparsable_falls_back_to_default(monkeypatch):
# GIVEN POWERTOOLS_TRACE_MIDDLEWARES has an empty value
monkeypatch.setenv("POWERTOOLS_TRACE_MIDDLEWARES", "")
monkeypatch.setenv("POWERTOOLS_TRACE_DISABLED", "true")

# WHEN a middleware is created
# THEN it should warn naming the variable instead of raising ValueError
with pytest.warns(PowertoolsUserWarning, match="POWERTOOLS_TRACE_MIDDLEWARES"):

@lambda_handler_decorator
def no_op(handler, event, context):
return handler(event, context)

@no_op
def lambda_handler(evt, ctx):
return True

assert lambda_handler({}, {}) is True
54 changes: 54 additions & 0 deletions tests/functional/tracer/_aws_xray_sdk/test_tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import pytest

from aws_lambda_powertools import Tracer
from aws_lambda_powertools.warnings import PowertoolsUserWarning


@pytest.fixture
Expand Down Expand Up @@ -228,3 +229,56 @@ def handler(event, context):
result = handler({}, {})
assert "testresult" in result
assert "testresult2" in result


@pytest.mark.parametrize("value", ["", "enabled", "true "])
def test_tracer_disabled_env_var_unparsable_falls_back_to_default(monkeypatch, service_name, value):
# GIVEN POWERTOOLS_TRACE_DISABLED has an empty or unparsable value
monkeypatch.setenv("POWERTOOLS_TRACE_DISABLED", value)

# WHEN Tracer is initialized
# THEN it should warn naming the variable instead of raising ValueError
with pytest.warns(PowertoolsUserWarning, match="POWERTOOLS_TRACE_DISABLED"):
tracer = Tracer(service=service_name)

assert tracer.service == service_name


@pytest.mark.parametrize("env_var", ["POWERTOOLS_TRACER_CAPTURE_RESPONSE", "POWERTOOLS_TRACER_CAPTURE_ERROR"])
def test_tracer_capture_env_var_unparsable_falls_back_to_default(monkeypatch, dummy_response, env_var):
# GIVEN a tracer capture env var has an empty value
monkeypatch.setenv(env_var, "")
tracer = Tracer(disabled=True)

# WHEN the handler and method decorators are applied
# THEN they should warn naming the variable instead of raising ValueError
with pytest.warns(PowertoolsUserWarning, match=env_var):

@tracer.capture_lambda_handler
def handler(event, context):
return dummy_response

with pytest.warns(PowertoolsUserWarning, match=env_var):

@tracer.capture_method
def greeting():
return dummy_response

assert handler({}, {}) == dummy_response
assert greeting() == dummy_response


def test_tracer_capture_explicit_choice_ignores_unparsable_env_var(monkeypatch, recwarn):
# GIVEN tracer capture env vars have unparsable values
monkeypatch.setenv("POWERTOOLS_TRACER_CAPTURE_RESPONSE", "")
monkeypatch.setenv("POWERTOOLS_TRACER_CAPTURE_ERROR", "")
tracer = Tracer(disabled=True)

# WHEN capture options are passed explicitly
@tracer.capture_lambda_handler(capture_response=False, capture_error=False)
def handler(event, context):
return True

# THEN the env vars should not be read
assert handler({}, {}) is True
assert not [w for w in recwarn if issubclass(w.category, PowertoolsUserWarning)]