Instrumenting a Go application for Prometheus
You can install the , promauto
, and promhttp
libraries necessary for the guide using go get
:
To expose Prometheus metrics in a Go application, you need to provide a /metrics
HTTP endpoint. You can use the library’s HTTP Handler
as the handler function.
This minimal application, for example, would expose the default metrics for Go applications via http://localhost:2112/metrics
:
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":2112", nil)
}
go run main.go
To access the metrics:
The application exposes only the default Go metrics. You can also register your own custom application-specific metrics. This example application exposes a myapp_processed_ops_total
counter that counts the number of operations that have been processed thus far. Every 2 seconds, the counter is incremented by one.
import (
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func recordMetrics() {
go func() {
for {
opsProcessed.Inc()
time.Sleep(2 * time.Second)
}
}()
}
var (
Help: "The total number of processed events",
})
)
func main() {
recordMetrics()
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":2112", nil)
}
To run the application:
go run main.go
In the metrics output, you’ll see the help text, type information, and current value of the myapp_processed_ops_total
counter:
# HELP myapp_processed_ops_total The total number of processed events
# TYPE myapp_processed_ops_total counter
myapp_processed_ops_total 5
You can a locally running Prometheus instance to scrape metrics from the application. Here’s an example prometheus.yml
configuration:
scrape_configs:
- job_name: myapp
scrape_interval: 10s
static_configs:
In this guide we covered just a small handful of features available in the Prometheus Go client libraries. You can also expose other metrics types, such as gauges and , non-global registries, functions for to Prometheus PushGateways, bridging Prometheus and , and more.