Exposing the Desired Metrics
Explore how to expose Go runtime metrics such as goroutines count and memory usage to Prometheus for effective monitoring. Learn to implement HTTP handlers that serve these metrics, use Go modules and external packages, and run the application with Docker. This lesson guides you through running and testing the metrics endpoint locally and preparing the environment for Prometheus integration.
We'll cover the following...
This lesson illustrates how to expose metrics from the runtime/metrics package to Prometheus. In our case, we use /sched/goroutines:goroutines and /memory/classes/total:bytes. We already know about the former, which is the total number of goroutines. The latter metric is the amount of memory mapped by the Go runtime into the current process as read-write.
Note: Because the presented code uses an external package, it should be put inside
~/go/srcand Go modules should be enabled usinggo mod init.
Coding example
The Go code of prometheus.go is as follows:
The first external package is the Go client library for Prometheus and the second package is for using the default handler function (promhttp.Handler()).
Here, we define the two Prometheus metrics.