Senior
Which libraries are used to write metrics in Go?
sobes.tech AI
Answer from AI
In Go, the most commonly used library for collecting and exporting metrics is Prometheus client_golang, which provides a convenient API for creating counters, histograms, summaries, and other metric types.
Example of usage:
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
)
var (
opsProcessed = prometheus.NewCounter(prometheus.CounterOpts{
Name: "myapp_processed_ops_total",
Help: "The total number of processed events",
})
)
func init() {
prometheus.MustRegister(opsProcessed)
}
func handler(w http.ResponseWriter, r *http.Request) {
opsProcessed.Inc()
w.Write([]byte("Hello, Metrics!"))
}
func main() {
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
For more complex cases, OpenTelemetry can be used, which supports collecting metrics, traces, and logs, and integrates with Prometheus and other monitoring systems.