Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
16 changes: 15 additions & 1 deletion homeassistant/components/prometheus/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Support for Prometheus metrics export."""
import logging
import string

from aiohttp import web
import voluptuous as vol
Expand Down Expand Up @@ -159,10 +160,23 @@ def _metric(self, metric, factory, documentation, labels=None):
try:
return self._metrics[metric]
except KeyError:
full_metric_name = f"{self.metrics_prefix}{metric}"
full_metric_name = self._sanitize_metric_name(
f"{self.metrics_prefix}{metric}"
)
self._metrics[metric] = factory(full_metric_name, documentation, labels)
return self._metrics[metric]

@staticmethod
def _sanitize_metric_name(metric: str) -> str:
return "".join(
[
c
if c in string.ascii_letters or c.isdigit() or c == "_" or c == ":"
else f"u{hex(ord(c))}"
for c in metric
]
)

@staticmethod
def state_as_number(state):
"""Return a state casted to a float."""
Expand Down
11 changes: 11 additions & 0 deletions tests/components/prometheus/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ async def prometheus_client(loop, hass, hass_client):
sensor3.entity_id = "sensor.electricity_price"
await sensor3.async_update_ha_state()

sensor4 = DemoSensor("Wind Direction", 25, None, "°", None)
sensor4.hass = hass
sensor4.entity_id = "sensor.wind_direction"
await sensor4.async_update_ha_state()

return await hass_client()


Expand Down Expand Up @@ -103,3 +108,9 @@ def test_view(prometheus_client): # pylint: disable=redefined-outer-name
'entity="sensor.electricity_price",'
'friendly_name="Electricity price"} 0.123' in body
)

assert (
'sensor_unit_u0xb0{domain="sensor",'
'entity="sensor.wind_direction",'
'friendly_name="Wind Direction"} 25.0' in body
)