Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(metrics): add warning for invalid dimension values; prevent their addition to EMF blobs #5542

Merged
merged 4 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -272,10 +272,18 @@ def add_dimension(self, name: str, value: str) -> None:
raise SchemaValidationError(
f"Maximum number of dimensions exceeded ({MAX_DIMENSIONS}): Unable to add dimension {name}.",
)
# Cast value to str according to EMF spec
# Majority of values are expected to be string already, so
# checking before casting improves performance in most cases
self.dimension_set[name] = value if isinstance(value, str) else str(value)

if not name or not value:
leandrodamascena marked this conversation as resolved.
Show resolved Hide resolved
warnings.warn(
f"The dimension {name} doesn't meet the requirements and won't be added. "
"Ensure the dimension name and value are non empty strings",
stacklevel=2,
)
else:
# Cast value to str according to EMF spec
# Majority of values are expected to be string already, so
# checking before casting improves performance in most cases
self.dimension_set[name] = value if isinstance(value, str) else str(value)

def add_metadata(self, key: str, value: Any) -> None:
"""Adds high cardinal metadata for metrics object
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1045,6 +1045,25 @@ def test_clear_default_dimensions(namespace):
assert not my_metrics.default_dimensions


def test_add_dimensions_with_empty_value(namespace, capsys, metric):
# GIVEN Metrics is initialized
my_metrics = Metrics(namespace=namespace)

my_dimension = "my_empty_dimension"

# WHEN we try to add a dimension with empty value
with pytest.warns(UserWarning, match=f"The dimension {my_dimension} doesn't meet the requirements *"):
my_metrics.add_dimension(name="my_empty_dimension", value="")

my_metrics.add_metric(**metric)
my_metrics.flush_metrics()

output = capture_metrics_output(capsys)

# THEN the serialized metric should not contain this dimension
assert my_dimension not in output


def test_get_and_set_namespace_and_service_properties(namespace, service, metrics, capsys):
# GIVEN Metrics instance is initialized without namespace and service
my_metrics = Metrics()
Expand Down