Skip to content

Commit 1f103e4

Browse files
Adding warning when dimension name or value is empty
1 parent 4a016af commit 1f103e4

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

aws_lambda_powertools/metrics/provider/cloudwatch_emf/cloudwatch.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -272,10 +272,18 @@ def add_dimension(self, name: str, value: str) -> None:
272272
raise SchemaValidationError(
273273
f"Maximum number of dimensions exceeded ({MAX_DIMENSIONS}): Unable to add dimension {name}.",
274274
)
275-
# Cast value to str according to EMF spec
276-
# Majority of values are expected to be string already, so
277-
# checking before casting improves performance in most cases
278-
self.dimension_set[name] = value if isinstance(value, str) else str(value)
275+
276+
if not name or not value:
277+
warnings.warn(
278+
f"The dimension {name} doesn't meet the requirements and won't be added. "
279+
"Ensure the dimension name and value are non empty strings",
280+
stacklevel=2,
281+
)
282+
else:
283+
# Cast value to str according to EMF spec
284+
# Majority of values are expected to be string already, so
285+
# checking before casting improves performance in most cases
286+
self.dimension_set[name] = value if isinstance(value, str) else str(value)
279287

280288
def add_metadata(self, key: str, value: Any) -> None:
281289
"""Adds high cardinal metadata for metrics object

tests/functional/metrics/required_dependencies/test_metrics_cloudwatch_emf.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1045,6 +1045,25 @@ def test_clear_default_dimensions(namespace):
10451045
assert not my_metrics.default_dimensions
10461046

10471047

1048+
def test_add_dimensions_with_empty_value(namespace, capsys, metric):
1049+
# GIVEN Metrics is initialized
1050+
my_metrics = Metrics(namespace=namespace)
1051+
1052+
my_dimension = "my_empty_dimension"
1053+
1054+
# WHEN we try to add a dimension with empty value
1055+
with pytest.warns(UserWarning, match=f"The dimension {my_dimension} doesn't meet the requirements *"):
1056+
my_metrics.add_dimension(name="my_empty_dimension", value="")
1057+
1058+
my_metrics.add_metric(**metric)
1059+
my_metrics.flush_metrics()
1060+
1061+
output = capture_metrics_output(capsys)
1062+
1063+
# THEN the serialized metric should not contain this dimension
1064+
assert my_dimension not in output
1065+
1066+
10481067
def test_get_and_set_namespace_and_service_properties(namespace, service, metrics, capsys):
10491068
# GIVEN Metrics instance is initialized without namespace and service
10501069
my_metrics = Metrics()

0 commit comments

Comments
 (0)