github.com/MetalBlockchain/metalgo@v1.11.9/api/server/metrics.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package server 5 6 import ( 7 "errors" 8 "net/http" 9 "time" 10 11 "github.com/prometheus/client_golang/prometheus" 12 ) 13 14 type metrics struct { 15 numProcessing *prometheus.GaugeVec 16 numCalls *prometheus.CounterVec 17 totalDuration *prometheus.GaugeVec 18 } 19 20 func newMetrics(registerer prometheus.Registerer) (*metrics, error) { 21 m := &metrics{ 22 numProcessing: prometheus.NewGaugeVec( 23 prometheus.GaugeOpts{ 24 Name: "calls_processing", 25 Help: "The number of calls this API is currently processing", 26 }, 27 []string{"base"}, 28 ), 29 numCalls: prometheus.NewCounterVec( 30 prometheus.CounterOpts{ 31 Name: "calls", 32 Help: "The number of calls this API has processed", 33 }, 34 []string{"base"}, 35 ), 36 totalDuration: prometheus.NewGaugeVec( 37 prometheus.GaugeOpts{ 38 Name: "calls_duration", 39 Help: "The total amount of time, in nanoseconds, spent handling API calls", 40 }, 41 []string{"base"}, 42 ), 43 } 44 45 err := errors.Join( 46 registerer.Register(m.numProcessing), 47 registerer.Register(m.numCalls), 48 registerer.Register(m.totalDuration), 49 ) 50 return m, err 51 } 52 53 func (m *metrics) wrapHandler(chainName string, handler http.Handler) http.Handler { 54 numProcessing := m.numProcessing.WithLabelValues(chainName) 55 numCalls := m.numCalls.WithLabelValues(chainName) 56 totalDuration := m.totalDuration.WithLabelValues(chainName) 57 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 58 startTime := time.Now() 59 numProcessing.Inc() 60 61 defer func() { 62 numProcessing.Dec() 63 numCalls.Inc() 64 totalDuration.Add(float64(time.Since(startTime))) 65 }() 66 67 handler.ServeHTTP(w, r) 68 }) 69 }