Search⌘ K
AI Features

Exposing Metrics

Understand how to expose Prometheus metrics in Go web services by defining and registering counters, gauges, histograms, and summaries. Learn to use promhttp handlers to serve metrics and verify outputs, enabling performance monitoring and bottleneck detection in production Go applications.

We'll cover the following...

Collecting metrics is a totally different task from exposing them for Prometheus to collect them. This lesson shows how to make the metrics available for collection.

Coding example

The code of samplePro.go is as follows:

Go (1.19.0)
package main
import (
"fmt"
"net/http"
"math/rand"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)

We need to use two external packages for communicating with Prometheus.

Go (1.19.0)
var PORT = ":1234"
var counter = prometheus.NewCounter(
prometheus.CounterOpts{
Namespace: "educative",
Name: "my_counter",
Help: "This is my counter",
})

This is how we define a new counter variable and specify the desired options. The Namespace field is very important because it allows us to group metrics in sets.

Go (1.19.0)
var gauge = prometheus.NewGauge(
prometheus.GaugeOpts{
Namespace: "educative",
Name: "my_gauge",
Help: "This is my gauge",
})

This is how we define a new ...