In this guide, we'll go over how to export metrics with Prometheus in a Go application. Prometheus is a powerful monitoring tool that collects metrics from configured targets at specified intervals. To get started, we will implement a simple HTTP server in Go that exports metrics for Prometheus to scrape.
First, ensure you have the Prometheus Go client library installed:
go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp
Below is an example of a basic Go application that exports a simple counter metric:
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
// Create a new counter metric
requestsCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
},
[]string{"method"},
)
)
func init() {
// Register the counter with Prometheus
prometheus.MustRegister(requestsCounter)
}
func handler(w http.ResponseWriter, r *http.Request) {
// Increment the counter
requestsCounter.WithLabelValues(r.Method).Inc()
w.Write([]byte("Hello, World!"))
}
func main() {
// Set up the metrics endpoint
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/", handler)
// Start the HTTP server
http.ListenAndServe(":8080", nil)
}
After running the application, you can access the metrics at /metrics
endpoint. Make sure to configure your Prometheus server to scrape this endpoint to collect the metrics.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?