При создании Gauge java micrometer получаю значение NaN
Хочу создать датчик количества новых соединений в java с использованием библиотеки Micrometer для Prometheus.
public static PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
private static AtomicInteger new_http_connection;
new_http_connection = Metrics.prometheusRegistry.gauge("new_http_connection", new AtomicInteger(0));
// Проверить тип запроса
if (request.equals("CONNECT")) {
handleHTTPSRequest(urlString);
new_http_connection.incrementAndGet();
System.out.println("CONNECT " + new_http_connection);
} else {
sendPageToClient(urlString);
}
В консоли я вижу количество новых соединений:
CONNECT 12
CONNECT 14
CONNECT 14
Но Prometheus выводит:
# HELP new_http_connection
# TYPE new_http_connection gauge
new_http_connection NaN
Ответы (1 шт):
По представленному коду не совсем понятно, каким именно образом создаются и изменяются значения датчиков.
Prometheus требует, чтобы сохранялись сильные ссылки на объекты состояния, которые измеряются при помощи датчика, о чём указано в документации:
Why is My Gauge Reporting NaN or Disappearing?
It is your responsibility to hold a strong reference to the state object that you are measuring with a
Gauge. Micrometer is careful to not create strong references to objects that would otherwise be garbage collected. Once the object being gauged is de-referenced and is garbage collected, Micrometer starts reporting a NaN or nothing for a gauge, depending on the registry implementation.If you see your gauge reporting for a few minutes and then disappearing or reporting NaN, it almost certainly suggests that the underlying object being gauged has been garbage collected.
Для решения этой проблемы следует создать долгоживущий объект, который не пострадает при сборке мусора:
public static PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
private static AtomicInteger newHttpConnection = new AtomicInteger(0);
Metrics.prometheusRegistry.gauge("new_http_connection", newHttpConnection);
Использование для инкремента как и раньше:
if ("CONNECT".equals(request)) {
handleHTTPSRequest(urlString);
System.out.println("CONNECT " + newHttpConnection.incrementAndGet());
} else {
sendPageToClient(urlString);
}
Аналогичный вопрос на основном SO от 12 июня 2018: Micrometer - Prometheus Gauge displays NaN