Skip to content

Commit b64be3b

Browse files
authored
Skip and log warning when lambda_metric called with invalid name or value (#553)
1 parent 7893e9b commit b64be3b

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

datadog_lambda/metric.py

+16
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,22 @@ def lambda_metric(metric_name, value, timestamp=None, tags=None, force_async=Fal
5555
Note that if the extension is present, it will override the DD_FLUSH_TO_LOG value
5656
and always use the layer to send metrics to the extension
5757
"""
58+
if not metric_name or not isinstance(metric_name, str):
59+
logger.warning(
60+
"Ignoring metric submission. Invalid metric name: %s", metric_name
61+
)
62+
return
63+
64+
try:
65+
float(value)
66+
except (ValueError, TypeError):
67+
logger.warning(
68+
"Ignoring metric submission for metric '%s' because the value is not numeric: %r",
69+
metric_name,
70+
value,
71+
)
72+
return
73+
5874
flush_to_logs = os.environ.get("DD_FLUSH_TO_LOG", "").lower() == "true"
5975
tags = [] if tags is None else list(tags)
6076
tags.append(dd_lambda_layer_tag)

tests/test_metric.py

+26
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,32 @@ def test_lambda_metric_flush_to_log(self):
9292

9393
del os.environ["DD_FLUSH_TO_LOG"]
9494

95+
@patch("datadog_lambda.metric.logger.warning")
96+
def test_lambda_metric_invalid_metric_name_none(self, mock_logger_warning):
97+
lambda_metric(None, 1)
98+
self.mock_metric_lambda_stats.distribution.assert_not_called()
99+
mock_logger_warning.assert_called_once_with(
100+
"Ignoring metric submission. Invalid metric name: %s", None
101+
)
102+
103+
@patch("datadog_lambda.metric.logger.warning")
104+
def test_lambda_metric_invalid_metric_name_not_string(self, mock_logger_warning):
105+
lambda_metric(123, 1)
106+
self.mock_metric_lambda_stats.distribution.assert_not_called()
107+
mock_logger_warning.assert_called_once_with(
108+
"Ignoring metric submission. Invalid metric name: %s", 123
109+
)
110+
111+
@patch("datadog_lambda.metric.logger.warning")
112+
def test_lambda_metric_non_numeric_value(self, mock_logger_warning):
113+
lambda_metric("test.non_numeric", "oops")
114+
self.mock_metric_lambda_stats.distribution.assert_not_called()
115+
mock_logger_warning.assert_called_once_with(
116+
"Ignoring metric submission for metric '%s' because the value is not numeric: %r",
117+
"test.non_numeric",
118+
"oops",
119+
)
120+
95121

96122
class TestFlushThreadStats(unittest.TestCase):
97123
def setUp(self):

0 commit comments

Comments
 (0)