IllegalArgumentException: metric name cannot contain whitespace when registering custom metrics
0 reputation · 06 Nov 2021, 06:47 UTC
0 reputation · 06 Nov 2021, 06:47 UTC
When adding a custom metric to Dropwizard’s MetricRegistry, the framework throws IllegalArgumentException: metric name cannot contain whitespace if the supplied name includes spaces. This exception is documented in the MetricRegistry Javadoc and is also the root cause of 400 responses from the /metrics endpoint when malformed names are registered programmatically.
The goal is to expose human‑readable metric names in the /metrics output while still conforming to Prometheus label constraints, which disallow spaces. The current implementation requires manual replacement or sanitization of names before registration.
Unresolved decisions:
35275 reputation · 06 Nov 2021, 14:25 UTC
Dropwizard’s MetricRegistry.register(String name, Metric metric) validates the supplied name via MetricName.build. The builder throws IllegalArgumentException: metric name cannot contain whitespace if any character in the name satisfies Character.isWhitespace (space, tab, newline, etc.). This behavior is documented in the MetricRegistry Javadoc and is the root cause of the 400 responses from the /metrics endpoint when malformed names are registered.
[a-zA-Z_:][a-zA-Z0-9_:]* and therefore cannot contain spaces.MetricName supports tags (labels) that are exported by the Prometheus reporter as Prometheus labels.String safeName = "Request Latency Seconds".replaceAll("\\s+", "_"); // request_latency_seconds
MetricName metricName = MetricName.builder()
.name(safeName) // Prometheus‑safe identifier
.tag("display_name", "Request Latency Seconds") // human‑readable label
.build();
metricRegistry.register(metricName, new Histogram());
io.dropwizard.metrics5:metrics-prometheus), the tag will appear as a Prometheus label, e.g.:# HELP request_latency_seconds Request Latency Seconds
# TYPE request_latency_seconds histogram
request_latency_seconds{display_name="Request Latency Seconds"} ...
The above steps assume you are exposing metrics via the Dropwizard Prometheus reporter. If you are using a different reporter or a custom endpoint, the tag may not be exported. Are you using the Dropwizard Prometheus reporter to serve the /metrics endpoint? Your answer will determine whether the tag‑based approach is sufficient or if you need to adjust your reporter configuration.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.