Support filtered scrape for Prometheus

See gh-21545
This commit is contained in:
Johnny Lim
2020-05-23 14:29:03 +09:00
committed by Stephane Nicoll
parent c848f80c27
commit cd1baf18fe
4 changed files with 57 additions and 7 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,19 +19,24 @@ package org.springframework.boot.actuate.metrics.export.prometheus;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Enumeration;
import java.util.Set;
import io.prometheus.client.Collector.MetricFamilySamples;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint;
import org.springframework.lang.Nullable;
/**
* {@link Endpoint @Endpoint} that outputs metrics in a format that can be scraped by the
* Prometheus server.
*
* @author Jon Schneider
* @author Johnny Lim
* @since 2.0.0
*/
@WebEndpoint(id = "prometheus")
@@ -44,10 +49,13 @@ public class PrometheusScrapeEndpoint {
}
@ReadOperation(produces = TextFormat.CONTENT_TYPE_004)
public String scrape() {
public String scrape(@Nullable Set<String> includedNames) {
try {
Writer writer = new StringWriter();
TextFormat.write004(writer, this.collectorRegistry.metricFamilySamples());
Enumeration<MetricFamilySamples> samples = (includedNames != null)
? this.collectorRegistry.filteredMetricFamilySamples(includedNames)
: this.collectorRegistry.metricFamilySamples();
TextFormat.write004(writer, samples);
return writer.toString();
}
catch (IOException ex) {