Instrumenting a Go application for Prometheus
NOTE: For comprehensive API documentation, see the GoDoc for Prometheus' various Go libraries.
You can install the , promauto
, and promhttp
libraries necessary for the guide using :
To expose Prometheus metrics in a Go application, you need to provide a /metrics
HTTP endpoint. You can use the prometheus/promhttp
library's HTTP as the handler function.
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":2112", nil)
}
To start the application:
go run main.go
To access the metrics:
The application above 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
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)
}
go run main.go
To access the metrics:
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 configure 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, you created two sample Go applications that expose metrics to Prometheus—-one that exposes only the default Go metrics and one that also exposes a custom Prometheus counter—-and configured a Prometheus instance to scrape metrics from those applications.