How to Instrument Go Code with Prometheus Metrics

Add the Prometheus client library, define and register metrics, and expose the /metrics endpoint to enable monitoring.

Instrument Go code for Prometheus by adding the client library, defining metrics, and exposing an HTTP endpoint for scraping.

import (
    "net/http"
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

var requestCount = prometheus.NewCounter(
    prometheus.CounterOpts{
        Name: "http_requests_total",
        Help: "Total number of HTTP requests.",
    },
)

func init() {
    prometheus.MustRegister(requestCount)
}

func main() {
    http.HandleFunc("/metrics", promhttp.Handler().ServeHTTP)
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        requestCount.Inc()
        w.Write([]byte("Hello"))
    })
    http.ListenAndServe(":8080", nil)
}
  1. Import the Prometheus client library and define your metrics using types like NewCounter or NewGauge.
  2. Register your metrics with prometheus.MustRegister inside an init() function.
  3. Serve the metrics by mounting promhttp.Handler() to the /metrics endpoint in your HTTP server.
  4. Increment or update your metrics within your application logic whenever the relevant event occurs.