下面列出了怎么用io.prometheus.client.exporter.common.TextFormat的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String securityToken =
(String) getServletContext().getAttribute(SECURITY_TOKEN);
if (securityToken != null) {
String authorizationHeader = req.getHeader("Authorization");
if (authorizationHeader == null
|| !authorizationHeader.startsWith(BEARER)
|| !securityToken.equals(
authorizationHeader.substring(BEARER.length() + 1))) {
resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
DefaultMetricsSystem.instance().publishMetricsNow();
PrintWriter writer = resp.getWriter();
getPrometheusSink().writeMetrics(writer);
writer.write("\n\n#Dropwizard metrics\n\n");
//print out dropwizard metrics used by ratis.
TextFormat.write004(writer,
CollectorRegistry.defaultRegistry.metricFamilySamples());
writer.flush();
}
@Test
public void export() throws IOException {
//create Ratis metrics
RaftLogMetrics instance = new RaftLogMetrics("instance");
instance.getRaftLogSyncTimer().update(10, TimeUnit.MILLISECONDS);
MetricRegistry dropWizardMetricRegistry =
instance.getRegistry().getDropWizardMetricRegistry();
//create and register prometheus collector
RatisDropwizardExports exports =
new RatisDropwizardExports(dropWizardMetricRegistry);
CollectorRegistry collector = new CollectorRegistry();
collector.register(new RatisDropwizardExports(dropWizardMetricRegistry));
//export metrics to the string
StringWriter writer = new StringWriter();
TextFormat.write004(writer, collector.metricFamilySamples());
System.out.println(writer.toString());
Assert.assertFalse("Instance name is not moved to be a tag",
writer.toString()
.contains("ratis_core_ratis_log_worker_instance_syncTime"));
}
public void handle(HttpExchange t) throws IOException {
String query = t.getRequestURI().getRawQuery();
ByteArrayOutputStream response = this.response.get();
response.reset();
OutputStreamWriter osw = new OutputStreamWriter(response);
TextFormat.write004(osw, registry.filteredMetricFamilySamples(parseQuery(query)));
osw.flush();
osw.close();
response.flush();
response.close();
t.getResponseHeaders().set("Content-Type", TextFormat.CONTENT_TYPE_004);
t.getResponseHeaders().set("Content-Length", String.valueOf(response.size()));
if (shouldUseCompression(t)) {
t.getResponseHeaders().set("Content-Encoding", "gzip");
t.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
final GZIPOutputStream os = new GZIPOutputStream(t.getResponseBody());
response.writeTo(os);
os.finish();
} else {
t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size());
response.writeTo(t.getResponseBody());
}
t.close();
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
if (getCommonMetricsFilter() != null && getCommonMetricsFilter().isActionEnabled() && action != null) {
String metricName = req.getParameter("metric");
if ("enable".equalsIgnoreCase(action)) {
getCommonMetricsFilter().enableMetric(metricName);
}
else if ("disable".equalsIgnoreCase(action)) {
getCommonMetricsFilter().disableMetric(metricName);
}
resp.getWriter().write("OK");
return;
}
try {
StringWriter writer = new StringWriter();
TextFormat.write004(writer, getCollectorRegistry().metricFamilySamples());
resp.setContentType(TextFormat.CONTENT_TYPE_004);
resp.getWriter().write(writer.toString());
} catch (IOException e) {
// This actually never happens since StringWriter::write() doesn't throw any IOException
throw new RuntimeException("Writing metrics failed", e);
}
}
@Override
public void handle(RoutingContext rc) {
MeterRegistry registry;
if (registryName == null) {
registry = BackendRegistries.getDefaultNow();
} else {
registry = BackendRegistries.getNow(registryName);
}
if (registry instanceof PrometheusMeterRegistry) {
PrometheusMeterRegistry prometheusMeterRegistry = (PrometheusMeterRegistry) registry;
rc.response()
.putHeader(HttpHeaders.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004)
.end(prometheusMeterRegistry.scrape());
} else {
String statusMessage = "Invalid registry: " + (registry != null ? registry.getClass().getName() : null);
rc.response()
.setStatusCode(500).setStatusMessage(statusMessage)
.end();
}
}
@Override
protected void doGet(
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws IOException {
String paramToken = httpServletRequest.getParameter("token");
String storedToken = secureTokenManager.getToken();
if (StringUtils.isNotBlank(storedToken) && !storedToken.equals(paramToken)) {
httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
httpServletResponse.setContentType(TextFormat.CONTENT_TYPE_004);
try (Writer writer = httpServletResponse.getWriter()) {
TextFormat.write004(writer, metricCollector.getRegistry().filteredMetricFamilySamples(parse(httpServletRequest)));
writer.flush();
}
}
@Override
protected void doGet(
final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse) throws IOException {
String paramToken = httpServletRequest.getParameter("token");
String storedToken = secureTokenManager.getToken();
if (StringUtils.isNotBlank(storedToken) && !storedToken.equals(paramToken)) {
httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
httpServletResponse.setContentType(TextFormat.CONTENT_TYPE_004);
try (Writer writer = httpServletResponse.getWriter()) {
TextFormat.write004(writer, metricCollector.getRegistry().filteredMetricFamilySamples(parse(httpServletRequest)));
writer.flush();
}
}
@Override
protected void doGet(
final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse) throws IOException {
String paramToken = httpServletRequest.getParameter("token");
String storedToken = secureTokenManager.getToken();
if (StringUtils.isNotBlank(storedToken) && !storedToken.equals(paramToken)) {
httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
httpServletResponse.setContentType(TextFormat.CONTENT_TYPE_004);
try (Writer writer = httpServletResponse.getWriter()) {
TextFormat.write004(writer, metricCollector.getRegistry().filteredMetricFamilySamples(parse(httpServletRequest)));
writer.flush();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType(TextFormat.CONTENT_TYPE_004);
List<ProbeResult> probeResults = metricsCache.get();
formatProbeResults(probeResults)
.forEach(formattedProbeResult -> {
try {
resp.getWriter().print(formattedProbeResult + "\n");
} catch (IOException e) {
logger.error("IO error occurred writing to /metrics page.", e);
}
});
try (Writer writer = resp.getWriter()) {
TextFormat.write004(writer, registry.filteredMetricFamilySamples(parse(req)));
writer.flush();
}
}
private ResponseEntity<String> buildAnswer(@Nullable String[] includedParam) throws IOException {
Set<String> params;
if (includedParam == null) {
params = Collections.emptySet();
} else {
params = new HashSet<>(Arrays.asList(includedParam));
}
Writer writer = new StringWriter();
try {
TextFormat.write004(writer, this.registry.filteredMetricFamilySamples(params));
writer.flush();
} finally {
writer.close();
}
return new ResponseEntity<>(writer.toString(), HttpStatus.OK);
}
@RequestMapping( value = "/metrics", method = RequestMethod.GET, produces = TextFormat.CONTENT_TYPE_004 )
@ResponseBody
public String scrape()
{
try
{
Writer writer = new StringWriter();
TextFormat.write004( writer, this.collectorRegistry.metricFamilySamples() );
return writer.toString();
}
catch ( IOException ex )
{
// This never happens since StringWriter::write() doesn't throw IOException
throw new UncheckedIOException( "Writing metrics failed", ex );
}
}
@Test
public void shouldWriteNiceMetricsOutput() throws IOException {
// given
HystrixPrometheusMetricsPublisher.builder().shouldExportDeprecatedMetrics(false).buildAndRegister();
TestHystrixCommand command = new TestHystrixCommand("any");
// when
command.execute();
// then
Writer writer = new FileWriter("target/sample.txt");
try {
TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
writer.flush();
} finally {
writer.close();
}
}
@Test
public void shouldHaveExponentialBuckets() throws IOException {
// given
HystrixPrometheusMetricsPublisher.builder().withExponentialBuckets().buildAndRegister();
TestHystrixCommand command = new TestHystrixCommand("any");
// when
command.execute();
// then
StringWriter writer = new StringWriter();
try {
TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
writer.flush();
} finally {
writer.close();
}
String result = writer.toString();
Assertions.assertThat(result).contains("le=\"0.001\"");
Assertions.assertThat(result).contains("le=\"2.5169093494697568\"");
}
@Test
public void shouldHaveLinearBuckets() throws IOException {
// given
HystrixPrometheusMetricsPublisher.builder().withLinearBuckets(0.1, 0.2, 3).buildAndRegister();
TestHystrixCommand command = new TestHystrixCommand("any");
// when
command.execute();
// then
StringWriter writer = new StringWriter();
try {
TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
writer.flush();
} finally {
writer.close();
}
String result = writer.toString();
Assertions.assertThat(result).contains("le=\"0.1\"");
Assertions.assertThat(result).contains("le=\"0.5\"");
}
@Test
public void shouldHaveDistinctBuckets() throws IOException {
// given
HystrixPrometheusMetricsPublisher.builder().withBuckets(0.1, 1.0).buildAndRegister();
TestHystrixCommand command = new TestHystrixCommand("any");
// when
command.execute();
// then
StringWriter writer = new StringWriter();
try {
TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
writer.flush();
} finally {
writer.close();
}
String result = writer.toString();
Assertions.assertThat(result).contains("le=\"0.1\"");
Assertions.assertThat(result).contains("le=\"1.0\"");
}
@Override
protected ResourceResponse newResourceResponse(Attributes attributes) {
ResourceResponse response = new ResourceResponse();
response.setLastModified(Time.now());
// response.setStatusCode(HttpServlet);
response.setContentType(TextFormat.CONTENT_TYPE_004);
response.disableCaching();
if (response.dataNeedsToBeWritten(attributes)) {
PageParameters params = attributes.getParameters();
Set<String> includedMetrics = new HashSet<>();
params.getValues("name").forEach((sv) -> {if(!sv.isEmpty()) includedMetrics.add(sv.toString()); });
response.setWriteCallback(createWriteCallback(CollectorRegistry.defaultRegistry, includedMetrics));
}
return response;
}
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
if (logger.isDebugEnabled()) {
logger.debug("PrometheusServer Do get called");
}
ServletOutputStream response = resp.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(response);
for(Function<ReportingContext, CollectorRegistry> mc : metricsCollectors) {
CollectorRegistry collectorRegistry = mc.apply(getReportingContext());
TextFormat.write004(osw, collectorRegistry.metricFamilySamples());
}
osw.flush();
osw.close();
response.flush();
response.close();
resp.setHeader("Content-Type", TextFormat.CONTENT_TYPE_004);
resp.setStatus(HttpURLConnection.HTTP_OK);
resp.flushBuffer();
}
@RequestMapping(
method = {RequestMethod.GET},
produces = { "*/*" }
)
@ResponseBody
public ResponseEntity value(
@RequestParam(value = "name[]", required = false, defaultValue = "") Set<String> name) {
if (!getDelegate().isEnabled()) {
// Shouldn't happen - MVC endpoint shouldn't be registered when delegate's
// disabled
return getDisabledResponse();
}
String result = delgate.writeRegistry(name);
return ResponseEntity.ok()
.header(CONTENT_TYPE, TextFormat.CONTENT_TYPE_004)
.body(result);
}
private HttpServer setupWebserver(Handler<AsyncResult<HttpServer>> listenHandler) {
String port = componentConfig.get("port");
Objects.requireNonNull(port, "Must specify port for scrape server to listen on");
return vertx.createHttpServer().requestHandler(request -> {
HttpServerResponse response = request.response();
StringWriter sw = new StringWriter();
try {
TextFormat.write004(sw, collectorRegistry.metricFamilySamples());
response.setStatusCode(200)
.putHeader("Content-Type", TextFormat.CONTENT_TYPE_004)
.setChunked(true)
.write(sw.toString());
} catch (Exception e) {
response.setStatusCode(500)
.write(Json.encode(e));
}
response.end();
}).listen(Integer.parseInt(port), listenHandler);
}
private void metricsRequest(final RoutingContext routingContext) {
final Set<String> names = new TreeSet<>(routingContext.queryParam("name[]"));
final HttpServerResponse response = routingContext.response();
vertx.<String>executeBlocking(
future -> {
try {
final ByteArrayOutputStream metrics = new ByteArrayOutputStream(16 * 1024);
final OutputStreamWriter osw = new OutputStreamWriter(metrics, StandardCharsets.UTF_8);
TextFormat.write004(
osw,
((PrometheusMetricsSystem) (metricsSystem))
.getRegistry()
.filteredMetricFamilySamples(names));
osw.flush();
osw.close();
metrics.flush();
metrics.close();
future.complete(metrics.toString(StandardCharsets.UTF_8.name()));
} catch (final IOException ioe) {
future.fail(ioe);
}
},
false,
(res) -> {
if (response.closed()) {
// Request for metrics closed before response was generated
return;
}
if (res.failed()) {
LOG.error("Request for metrics failed", res.cause());
response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).end();
} else {
response.setStatusCode(HttpResponseStatus.OK.code());
response.putHeader("Content-Type", TextFormat.CONTENT_TYPE_004);
response.end(res.result());
}
});
}
@Test
public void registerToDefault() throws IOException {
when(metricProducer.getAllMetrics()).thenReturn(generateTestData());
StringWriter stringWriter = new StringWriter();
TextFormat.write004(stringWriter, CollectorRegistry.defaultRegistry.metricFamilySamples());
assertThat(stringWriter.toString())
.isEqualTo(
"# HELP grpc_name long_description\n"
+ "# TYPE grpc_name counter\n"
+ "grpc_name{kc=\"vc\",kp=\"vp\",} 5.0\n"
+ "# HELP http_name double_description\n"
+ "# TYPE http_name counter\n"
+ "http_name{kc=\"vc\",kp=\"vp\",} 3.5\n");
}
@GET
@Produces({MediaType.TEXT_PLAIN})
public Response getMetrics() {
Enumeration<Collector.MetricFamilySamples> mfs = prometheusRegistry.metricFamilySamples();
StreamingOutput stream = os -> {
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
TextFormat.write004(writer, mfs);
writer.flush();
};
return Response.ok(stream).build();
}
@Override
public ResponseEntity<String> invoke() {
try {
Writer writer = new StringWriter();
TextFormat.write004(writer, collectorRegistry.metricFamilySamples());
return ResponseEntity.ok()
.header(CONTENT_TYPE, TextFormat.CONTENT_TYPE_004)
.body(writer.toString());
} catch (IOException e) {
// This actually never happens since StringWriter::write() doesn't throw any IOException
throw new RuntimeException("Writing metrics failed", e);
}
}
@Override
public void initialize(GenericApplicationContext applicationContext) {
var environment = applicationContext.getEnvironment();
if (!environment.acceptsProfiles(Profiles.of("exporter"))) {
return;
}
applicationContext.registerBean(MetricsCollector.class);
applicationContext.registerBean("prometheus", RouterFunction.class, () -> {
var metricsCollector = applicationContext.getBean(MetricsCollector.class);
return RouterFunctions.route()
.GET("/prometheus", __ -> {
return metricsCollector.collect()
.collectList()
.flatMap(metrics -> {
try {
var writer = new StringWriter();
TextFormat.write004(writer, Collections.enumeration(metrics));
return ServerResponse.ok()
.contentType(MediaType.valueOf(TextFormat.CONTENT_TYPE_004))
.bodyValue(writer.toString());
} catch (IOException e) {
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
});
})
.build();
});
}
private void handleRequest(HttpServerRequest request) {
if (options.getEmbeddedServerEndpoint().equals(request.path())) {
request.response()
.putHeader(HttpHeaders.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004)
.end(registry.scrape());
} else {
request.response().setStatusCode(404).end();
}
}
public String toType004String() {
Enumeration<MetricFamilySamples> resultEMFS = this.getEnumerationMetricFamilySamples();
Writer writer = new StringWriter();
try {
TextFormat.write004(writer, resultEMFS);
} catch (IOException e) {
log.error("IO Exception on StringWriter; uuuhhh...", e);
}
return writer.toString();
}
@GetMapping(produces=TextFormat.CONTENT_TYPE_004)
public ResponseEntity<String> getMetrics(
@PathVariable String applicationId,
@PathVariable String instanceNumber
) {
if (this.isLoopbackRequest()) {
throw new LoopbackScrapingDetectedException("Erroneous Loopback Scraping request detected");
}
String instanceId = String.format("%s:%s", applicationId, instanceNumber);
String response = null;
try {
response = this.handleRequest( discoveredApplicationId -> applicationId.equals(discoveredApplicationId)
, requestInstance -> {
if (requestInstance.getInstanceId().equals(instanceId)) {
this.instance = requestInstance;
return true;
}
return false;
});
} catch (ScrapingException e) {
return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
@GetMapping(produces=TextFormat.CONTENT_TYPE_004)
public String getMetrics() {
HashMap<String, MetricFamilySamples> mfsMap = this.gmfspr.determineEnumerationOfMetricFamilySamples(this.collectorRegistry);
MergableMetricFamilySamples mmfs = new MergableMetricFamilySamples();
mmfs.merge(mfsMap);
return mmfs.toType004String();
}
@GetMapping(produces=TextFormat.CONTENT_TYPE_004)
public ResponseEntity<String> getMetrics() {
if (this.isLoopbackRequest()) {
throw new LoopbackScrapingDetectedException("Erroneous Loopback Scraping request detected");
}
try {
String result = this.handleRequest(null, null /* no filtering intended */);
return new ResponseEntity<>(result, HttpStatus.OK);
} catch (ScrapingException e) {
return new ResponseEntity<>(e.toString(), HttpStatus.SERVICE_UNAVAILABLE);
}
}
@Override
public String getTextFormat() {
try {
StringWriter result = new StringWriter();
TextFormat.write004(result, registry.metricFamilySamples());
return result.toString();
} catch (IOException e) {
throw new RuntimeException("Unexpected error when writing metrics to a String: " + e.getMessage(), e);
}
}