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)
}
- Import the Prometheus client library and define your metrics using types like
NewCounterorNewGauge. - Register your metrics with
prometheus.MustRegisterinside aninit()function. - Serve the metrics by mounting
promhttp.Handler()to the/metricsendpoint in your HTTP server. - Increment or update your metrics within your application logic whenever the relevant event occurs.