package observability import ( "strconv" "github.com/gin-gonic/gin" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "github.com/prometheus/client_golang/prometheus/promhttp" ) var ( // Variables that are to be registered with prometheus. promauto // automactically registers the variable with prometheus. If promauto is not // used variable needs to be registered using prometheus.register. Subscribers = promauto.NewGaugeVec( prometheus.GaugeOpts{ Name: "edge_interlock_subscribers", Help: "Current number of subscribers to Interlock API topics", }, []string{}) EventsTotal = promauto.NewCounterVec( prometheus.CounterOpts{ Name: "edge_interlock_events_total", Help: "Total number of update events sent off to subscribers by the Interlock API", }, []string{"topic"}) RequestsTotal = promauto.NewCounterVec( prometheus.CounterOpts{ Name: "edge_interlock_http_requests_total", Help: "Total number of requests made to the Interlock API", }, []string{"handler", "method", "status"}) RequestDuration = promauto.NewHistogramVec( prometheus.HistogramOpts{ Name: "edge_interlock_request_duration_seconds", Help: "Latency/duration of requests made to the Interlock API", Buckets: prometheus.LinearBuckets(0.0, 0.2, 10), }, []string{"handler", "method", "status"}) ) // MetricsEndpoint is the API endpoint where the prometheus metrics are served. var MetricsEndpoint = "/metrics" type Metrics struct{} // NewMetrics returns a new Metrics instance. func NewMetrics() *Metrics { return &Metrics{} } // RegisterEndpoints registers the promhttp handler onto the router. func (m *Metrics) RegisterEndpoints(r *gin.Engine) { r.GET( MetricsEndpoint, gin.WrapH(promhttp.Handler()), ) } // RecordSubscribers updates the Subscribers metric with the current number of // subscribers. func RecordSubscribers(count int) { countFloat := float64(count) Subscribers.WithLabelValues().Set(countFloat) } // RecordEvent increments the event counter for the provided topic. func RecordEvent(topic string) { EventsTotal.WithLabelValues(topic).Inc() } // RecordRequest increments the request counter for the request total metric and // observes the latency for the request duration metric, both with the provided // handler, method and status. func RecordRequest(handler, method string, status int, latency float64) { statusAsStr := strconv.Itoa(status) labels := map[string]string{ "handler": handler, "method": method, "status": statusAsStr, } RequestsTotal.With(labels).Inc() RequestDuration.With(labels).Observe(latency) }