Sobes.tech
Senior

What are metrics (Prometheus)? How does it collect data?

sobes.tech AI

Answer from AI

Prometheus is an open-source monitoring and metrics collection system widely used for observing the state of applications and infrastructure.

Metrics in Prometheus are numerical data that describe the state of the system at a specific point in time. They come in several types: counters, histograms, summaries, and gauges.

Data collection occurs via a pull model: Prometheus periodically scrapes HTTP endpoints that export metrics in a specific format. Typically, applications or services run an HTTP server with /metrics, where Prometheus reads the current metric values in a text format.

Example of exporting metrics in Go using the Prometheus library:

import (
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
    "net/http"
)

var opsProcessed = prometheus.NewCounter(prometheus.CounterOpts{
    Name: "myapp_processed_ops_total",
    Help: "The total number of processed events",
})

func init() {
    prometheus.MustRegister(opsProcessed)
}

func main() {
    http.Handle("/metrics", promhttp.Handler())
    go func() {
        for {
            opsProcessed.Inc() // increment the counter
            time.Sleep(time.Second)
        }
    }()
    http.ListenAndServe(":2112", nil)
}

Thus, Prometheus regularly requests /metrics and collects the current values for subsequent storage and analysis.

What are metrics (Prometheus)? How does it collect… - sobes.tech