...

/

Adding Metrics to the Application

Adding Metrics to the Application

Learn about integrating Prometheus metrics into our application to enhance observability and monitoring capabilities.

We will be using Prometheus to instrument our application to report metrics. Prometheus is quick to set up and just as quick to use.

Setting up the Prometheus endpoint for metrics collection

To begin, we need to set up an endpoint on the HTTP server so that Prometheus can fetch the metrics we will be publishing. Unlike OpenTelemetry, which uses a push model to send data to the collector, Prometheus uses a pull model and will need to be told where to look for metrics data.

To provide Prometheus with an endpoint to fetch the data, we need to import the promhttp package and then add the handler it provides to the HTTP server. We must modify the /internal/system/system.go file to add the endpoint:

Press + to interact
import (
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// ... much further down
func (s *System) initMux() {
s.mux = chi.NewMux()
s.mux.Use(middleware.Heartbeat("/liveness"))
s.mux.Method("GET", "/metrics", promhttp.Handler())
}

Prometheus expects to find metrics at the /metrics path by default, but that can be changed when we configure Prometheus to fetch the data.

The Go client for Prometheus automatically sets up a bunch of metrics for our application. Hitting that endpoint will display a dizzying list of metrics that were set up for us for free. We can also set up custom metrics for our application; to demonstrate, we will start with the messaging system.

When publishing a message, we must use a counter to record a total count and a count for that specific ...