Sobes.tech
Junior — Middle

How is metric collection performed using the Prometheus system?

sobes.tech AI

Answer from AI

Prometheus collects metrics using a pull model: it periodically scrapes HTTP endpoints that expose metrics in a format understood by Prometheus. In Go applications, the common approach is to use the Prometheus client library, which allows creating and updating metrics (counters, histograms, gauges, etc.). The application then runs an HTTP server with an endpoint (usually /metrics) where these metrics are available for collection.

Example in Go:

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

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 counter
            time.Sleep(time.Second)
        }
    }()
    http.ListenAndServe(":2112", nil)
}

The Prometheus server is configured to scrape http://yourapp:2112/metrics and collect data for analysis.