HikariCP have support to expose metrics for Prometheus thanks to the contribution of the community. This pull request make really easy to expose metrics to prometheus.
There are three simple Steps:
HikariDataSource(HikariConfig().apply {
driverClassName = "org.h2.Driver"
jdbcUrl = "jdbc:h2:mem:test"
maximumPoolSize = 5
isAutoCommit = true
transactionIsolation = "TRANSACTION_REPEATABLE_READ"
leakDetectionThreshold = 10000
poolName = "sat"
metricsTrackerFactory = PrometheusMetricsTrackerFactory()
validate()
}) |
To create the controller you can use the setMetricsTrackerFactory method on the config to set the registry with an instance of com.zaxxer.hikari.metrics.prometheus.PrometheusMetricsTrackerFactory. Also it is recommended to give a name for the pool in case if you have different Hikari pools exposing metrics. This will collect the metrics to the the default registry.
To expose the metrics for prometheus using ktor framework - and using routing feature - just need to create a new handler. This handle will respond with the metrics collected on the default registry. The endpoint "/metrics" the the default for prometheus.
package metrics
import com.proj.common.io.http.ApiContentType
import io.ktor.application.call
import io.ktor.response.respondTextWriter
import io.ktor.routing.Route
import io.ktor.routing.accept
import io.ktor.routing.get
import io.prometheus.client.CollectorRegistry
import io.prometheus.client.exporter.common.TextFormat
fun Route.metricsHandler() {
accept(ApiContentType.v1.test) {
get("/metrics") {
call.respondTextWriter{
TextFormat.write004(this, CollectorRegistry.defaultRegistry.metricFamilySamples())
}
}
}
} |