How to Use Prometheus Client Library in Go

Install the Prometheus Go client, define metrics, register them, and serve them at /metrics to enable monitoring.

Use the github.com/prometheus/client_golang library to create metrics and expose them via an HTTP endpoint.

  1. Install the library with go get github.com/prometheus/client_golang/prometheus.
  2. Import the package and define your metrics in your main file.
  3. Register your metrics with prometheus.DefaultRegisterer.
  4. Serve the metrics at /metrics using http.Handle.
package main

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

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

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

func main() {
	http.Handle("/metrics", promhttp.Handler())
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		requestsTotal.Inc()
		w.Write([]byte("Hello World"))
	})
	http.ListenAndServe(":8080", nil)
}