The Micrometer library is a popular way to expose application metrics to a service like Prometheus.
To add the Micrometer dependency for Prometheus with Maven:
<dependencies>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>${micrometer.version}</version>
</dependency>
</dependencies>
If you’re using Gradle instead:
dependencies {
implementation 'io.micrometer:micrometer-registry-prometheus:latest.release'
}
See the releases page for the latest version.
With the correct dependencies in place, you’re ready to expose metrics.
For exposing application metrics, you have two options:
The following example uses the JDK’s com.sun.net.httpserver.HttpServer
to
expose a /prometheus
endpoint. The PrometheusMeterRegistry
contains a
scrape()
function, which can supply the metric data to Prometheus. All you
need to do is wire the function to an endpoint.
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);
}
First, update the scope and remove the version of the
micrometer-registry-prometheus
dependency. Then add the
spring-boot-starter-actuator
dependency to your project.
Maven:
<dependencies>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
Gradle:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
runtimeOnly 'io.micrometer:micrometer-registry-prometheus'
}
Next, enable the Prometheus actuator endpoint. At the time of writing, you must
add prometheus
to the list of exposed Spring Boot Actuator endpoints. Your
endpoint configuration might look like the following:
management.endpoints.web.exposure.include: info, health, prometheus
This exposes metrics at the /actuator/prometheus
endpoint.