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.

    1. package main
    2. import (
    3. "net/http"
    4. "github.com/prometheus/client_golang/prometheus/promhttp"
    5. )
    6. func main() {
    7. http.Handle("/metrics", promhttp.Handler())
    8. http.ListenAndServe(":2112", nil)
    9. }

    To start the application:

    1. 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.

    1. import (
    2. "net/http"
    3. "time"
    4. "github.com/prometheus/client_golang/prometheus"
    5. "github.com/prometheus/client_golang/prometheus/promauto"
    6. "github.com/prometheus/client_golang/prometheus/promhttp"
    7. )
    8. func recordMetrics() {
    9. go func() {
    10. for {
    11. opsProcessed.Inc()
    12. time.Sleep(2 * time.Second)
    13. }
    14. }()
    15. }
    16. var (
    17. Help: "The total number of processed events",
    18. })
    19. )
    20. func main() {
    21. recordMetrics()
    22. http.Handle("/metrics", promhttp.Handler())
    23. http.ListenAndServe(":2112", nil)
    24. }
    1. 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:

    1. # HELP myapp_processed_ops_total The total number of processed events
    2. # TYPE myapp_processed_ops_total counter
    3. 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:

    1. scrape_configs:
    2. - job_name: myapp
    3. scrape_interval: 10s
    4. 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.