package eu.dnetlib.common.metrics; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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; import io.prometheus.client.exporter.common.TextFormat; @Component public class MetricUtils { @Autowired(required = false) private Map kpiMetrics; private static final Log log = LogFactory.getLog(MetricUtils.class); @PostConstruct public void registerToMainEndpoint() { if (kpiMetrics != null) { kpiMetrics.forEach((k, v) -> Metrics.gauge(k, v, o -> o.obtainValue())); log.info("KPI METRICS REGISTERED: " + StringUtils.join(kpiMetrics.keySet(), ", ")); } } public String output(final String contentType) { try { final List samples = new ArrayList<>(); if (kpiMetrics != null) { kpiMetrics.forEach((k, v) -> samples.add(new GaugeMetricFamily(k, "", v.obtainValue()))); } final Writer writer = new StringWriter(); TextFormat.writeFormat(contentType, writer, Collections.enumeration(samples)); 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); } } }