Reputation: 440
I would like to expose Prometheus metrics to an endpoint. I don't have spring-boot so I need to expose metrics on my own.
I took example code from:
https://micrometer.io/docs/registry/prometheus#_configuring
PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
try {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/prometheus", httpExchange -> {
String response = prometheusRegistry.scrape(); (1)
httpExchange.sendResponseHeaders(200, response.getBytes().length);
try (OutputStream os = httpExchange.getResponseBody()) {
os.write(response.getBytes());
}
});
new Thread(server::start).start();
} catch (IOException e) {
throw new RuntimeException(e);
}
While it works, I would like to avoid using sun package. Is there a way to do this as short and elegant with netty, okhttp or apache for example?
Thank you.
Upvotes: 1
Views: 1711
Reputation: 4245
You may use this piece of code:
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
server.setHandler(context);
context.addServlet(new ServletHolder(new MetricsServlet()), "/prometheus");
There are no sun packages in imports, only Jetty and Prometheus Java client:
import io.prometheus.client.exporter.MetricsServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
Upvotes: 4