After registering our metrics with Prometheus and instrumenting our code to update them where needed, the only additional thing that we need to do is expose the collected values over HTTP so that Prometheus can scrape them.
The promhttp subpackage from the Prometheus client package provides a convenience helper function called Handler that returns an http.Handler instance that encapsulates all the required logic for exporting collected metrics in the format expected by Prometheus.
The exported data will not only include the metrics that have been registered by the developer but it will also contain an extensive list of metrics that pertain to the Go runtime. Some examples of such metrics are as follows:
- The number of active goroutines
- Information about stack and heap allocation
- Performance statistics for the Go garbage collector
The following example demonstrates a minimal, self-contained hello-world kind of application that defines a counter metric and exposes two HTTP routes: /ping and /metrics. The handler for the first route increments the counter, while the latter exports the collected Prometheus metrics:
func main() { // Create a prometheus counter to keep track of ping requests. numPings := promauto.NewCounter(prometheus.CounterOpts{ Name: "pingapp_pings_total", Help: "The total number of incoming ping requests", }) http.Handle("/metrics", promhttp.Handler()) http.Handle("/ping", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { numPings.Inc() w.Write([]byte("pong!\n")) })) log.Fatal(http.ListenAndServe(":8080", nil)) }
Try to compile and run the preceding example. You can find its sources in the Chapter13/prom_http folder in this book's GitHub repository. While the example is running, switch to another Terminal and execute a few curl localhost:8080/ping commands to increment the pingapp_pings_total counter.
Then, execute a curl localhost:8080/metrics command and examine the list of exported metrics. The following screenshot displays the last few lines of output upon executing the preceding command:
As you can see, the output includes not only the current value of the pingapp_pings_total counter but also several other important metrics that the Prometheus client automatically captured from the Go runtime for us.