prometheus – how to create custom gauges with Spring Boot and Micrometer?
prometheus – how to create custom gauges with Spring Boot and Micrometer?
The objects that you are using are getting garbage collected since noting is holding onto a reference of those values. Gauges use weak references by default.
If you set it to use strong references it should avoid the NaN
s. Unfortunately the global registry helpers dont expose the gauge builder so youll need to create the gauge a little differently.
Gauge.builder(humidity, humidity, humidity -> sensorReading.getHumidity()).strongReference(true).register(Metrics.globalRegistry);
As a side note I would recommend moving away from the @Scheduled
approach unless the sensor reading is inherently slow. If the SensorReader
is thread safe, you could remove the @Scheduled
and use the SensorReader
directly:
SensorReader sensorReader = new SensorReader();
Gauge.builder(humidity, sensorReader, sensorReader ->
sensorReader.getSensorReading().getHumidity())
.strongReference(true)
.register(Metrics.globalRegistry);
Gauge.builder(fahrenheit, sensorReader, sensorReader ->
sensorReader.getSensorReading().getFahrenheit())
.strongReference(true)
.register(Metrics.globalRegistry);
That way youll only be looking up the sensor reading are the rate that Prometheus is scraping the metrics.