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
11 changes: 11 additions & 0 deletions aws_lambda_powertools/metrics/provider/datadog/datadog.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import json
import logging
import math
import numbers
import os
import re
Expand All @@ -15,6 +16,7 @@
from aws_lambda_powertools.metrics.provider.datadog.warnings import DatadogDataValidationWarning
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import resolve_env_var_choice, strtobool
from aws_lambda_powertools.warnings import PowertoolsUserWarning

if TYPE_CHECKING:
from aws_lambda_powertools.shared.types import AnyCallableT
Expand Down Expand Up @@ -119,6 +121,15 @@ def add_metric(
if not isinstance(value, numbers.Real):
raise MetricValueError(f"{value} is not a valid number")

if not math.isfinite(value):
warnings.warn(
f"The metric {name} has a non-finite value ({value}) and won't be added. "
"Datadog only accepts finite numbers.",
category=PowertoolsUserWarning,
stacklevel=2,
)
return

if not timestamp:
timestamp = int(time.time())

Expand Down
3 changes: 3 additions & 0 deletions docs/core/metrics/datadog.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ By default, we will generate the current timestamp for you. Alternatively, you c
--8<-- "examples/metrics_datadog/src/add_metrics_with_timestamp.py"
```

???+ note "Note: Non-finite values"
Datadog only accepts finite numbers. `add_metric` skips a `NaN` or infinite value and emits a `PowertoolsUserWarning`.

???+ warning "Warning: Do not create metrics outside the handler"
Metrics added in the global scope will only be added during cold start. Disregard if you that's the intended behavior.

Expand Down
24 changes: 24 additions & 0 deletions tests/functional/metrics/datadog/test_metrics_datadog.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from aws_lambda_powertools.metrics.exceptions import MetricValueError, SchemaValidationError
from aws_lambda_powertools.metrics.provider.cold_start import reset_cold_start_flag
from aws_lambda_powertools.metrics.provider.datadog import DatadogMetrics, DatadogProvider
from aws_lambda_powertools.warnings import PowertoolsUserWarning


def test_datadog_coldstart(capsys):
Expand Down Expand Up @@ -125,6 +126,29 @@ def test_datadog_with_invalid_metric_value():
metrics.add_metric(name="item_sold", value="a", product="latte", order="online")


def _reject_non_finite(constant: str):
raise ValueError(f"Datadog output contains {constant}, which is not valid JSON")


@pytest.mark.parametrize("value", [float("nan"), float("inf"), float("-inf")])
def test_datadog_add_metric_with_non_finite_value(capsys, value):
# GIVEN DatadogMetrics is initialized with flush_to_log
dd_provider = DatadogProvider(flush_to_log=True)
metrics = DatadogMetrics(provider=dd_provider)

# WHEN we add a non-finite metric value next to a valid metric
with pytest.warns(PowertoolsUserWarning, match="The metric bad_metric has a non-finite value *"):
metrics.add_metric(name="bad_metric", value=value)
metrics.add_metric(name="good_metric", value=1.0)
metrics.flush_metrics()

# THEN the flushed log is valid JSON and only contains the valid metric
output = capsys.readouterr().out.strip()
logs = json.loads(output, parse_constant=_reject_non_finite)
assert logs["m"] == "good_metric"
assert logs["v"] == 1.0


def test_datadog_with_invalid_metric_name():
# GIVEN DatadogMetrics is initialized
metrics = DatadogMetrics()
Expand Down