Skip to content

Commit

Permalink
Skip and log warning when lambda_metric called with invalid name or…
Browse files Browse the repository at this point in the history
… value (#553)
  • Loading branch information
nhulston authored Jan 30, 2025
1 parent 7893e9b commit b64be3b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
16 changes: 16 additions & 0 deletions datadog_lambda/metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,22 @@ def lambda_metric(metric_name, value, timestamp=None, tags=None, force_async=Fal
Note that if the extension is present, it will override the DD_FLUSH_TO_LOG value
and always use the layer to send metrics to the extension
"""
if not metric_name or not isinstance(metric_name, str):
logger.warning(
"Ignoring metric submission. Invalid metric name: %s", metric_name
)
return

try:
float(value)
except (ValueError, TypeError):
logger.warning(
"Ignoring metric submission for metric '%s' because the value is not numeric: %r",
metric_name,
value,
)
return

flush_to_logs = os.environ.get("DD_FLUSH_TO_LOG", "").lower() == "true"
tags = [] if tags is None else list(tags)
tags.append(dd_lambda_layer_tag)
Expand Down
26 changes: 26 additions & 0 deletions tests/test_metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,32 @@ def test_lambda_metric_flush_to_log(self):

del os.environ["DD_FLUSH_TO_LOG"]

@patch("datadog_lambda.metric.logger.warning")
def test_lambda_metric_invalid_metric_name_none(self, mock_logger_warning):
lambda_metric(None, 1)
self.mock_metric_lambda_stats.distribution.assert_not_called()
mock_logger_warning.assert_called_once_with(
"Ignoring metric submission. Invalid metric name: %s", None
)

@patch("datadog_lambda.metric.logger.warning")
def test_lambda_metric_invalid_metric_name_not_string(self, mock_logger_warning):
lambda_metric(123, 1)
self.mock_metric_lambda_stats.distribution.assert_not_called()
mock_logger_warning.assert_called_once_with(
"Ignoring metric submission. Invalid metric name: %s", 123
)

@patch("datadog_lambda.metric.logger.warning")
def test_lambda_metric_non_numeric_value(self, mock_logger_warning):
lambda_metric("test.non_numeric", "oops")
self.mock_metric_lambda_stats.distribution.assert_not_called()
mock_logger_warning.assert_called_once_with(
"Ignoring metric submission for metric '%s' because the value is not numeric: %r",
"test.non_numeric",
"oops",
)


class TestFlushThreadStats(unittest.TestCase):
def setUp(self):
Expand Down

0 comments on commit b64be3b

Please sign in to comment.