Exporting metrics for scraping

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 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:

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:

Figure 2: A subset of the metrics that have been exported by our example Go application

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.