dnet-applications/libs/dnet-apps-common/src/main/java/eu/dnetlib/common/metrics/MetricUtils.java

57 lines
1.7 KiB
Java
Raw Normal View History

2021-11-26 16:31:31 +01:00
package eu.dnetlib.common.metrics;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
2021-11-29 13:37:27 +01:00
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
2021-11-26 16:31:31 +01:00
2021-11-29 13:37:27 +01:00
import javax.annotation.PostConstruct;
2021-11-29 14:43:45 +01:00
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
2021-11-29 13:37:27 +01:00
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.micrometer.core.instrument.Metrics;
import io.prometheus.client.Collector.MetricFamilySamples;
import io.prometheus.client.GaugeMetricFamily;
2021-11-26 16:31:31 +01:00
import io.prometheus.client.exporter.common.TextFormat;
2021-11-29 13:37:27 +01:00
@Component
2021-11-26 16:31:31 +01:00
public class MetricUtils {
2021-11-29 13:37:27 +01:00
@Autowired(required = false)
private Map<String, MetricInfo> kpiMetrics;
2021-11-26 16:31:31 +01:00
2021-11-29 14:43:45 +01:00
private static final Log log = LogFactory.getLog(MetricUtils.class);
2021-11-29 13:37:27 +01:00
@PostConstruct
public void registerToMainEndpoint() {
if (kpiMetrics != null) {
kpiMetrics.forEach((k, v) -> Metrics.gauge(k, v, o -> o.obtainValue()));
2021-11-29 14:43:45 +01:00
log.info("KPI METRICS REGISTERED: " + StringUtils.join(kpiMetrics.keySet(), ", "));
2021-11-29 13:37:27 +01:00
}
2021-11-26 16:31:31 +01:00
}
2021-11-29 13:37:27 +01:00
public String output(final String contentType) {
2021-11-26 16:31:31 +01:00
try {
2021-11-29 13:37:27 +01:00
final List<MetricFamilySamples> samples = new ArrayList<>();
if (kpiMetrics != null) {
kpiMetrics.forEach((k, v) -> samples.add(new GaugeMetricFamily(k, "", v.obtainValue())));
}
2021-11-26 16:31:31 +01:00
final Writer writer = new StringWriter();
2021-11-29 13:37:27 +01:00
TextFormat.writeFormat(contentType, writer, Collections.enumeration(samples));
2021-11-26 16:31:31 +01:00
return writer.toString();
} catch (final IOException e) {
// This actually never happens since StringWriter::write() doesn't throw any IOException
throw new RuntimeException("Writing metrics failed", e);
}
}
}