package metrics import ( "expvar" "strconv" "time" "github.com/prometheus/client_golang/prometheus" ) var ( Registry = prometheus.NewRegistry() HTTPRequestsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "http_requests_total", Help: "Total number of HTTP requests by method, normalized path, and status.", }, []string{"method", "path", "status"}) HTTPRequestDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{ Name: "http_request_duration_seconds", Help: "HTTP request duration by method, normalized path, and status.", Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}, }, []string{"method", "path", "status"}) DBQueryDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{ Name: "db_query_duration_seconds", Help: "Database operation duration by driver, operation, and status.", Buckets: []float64{0.001, 0.003, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5}, }, []string{"driver", "operation", "status"}) WSConnectionsActive = prometheus.NewGaugeFunc(prometheus.GaugeOpts{ Name: "ws_connections_active", Help: "Current active WebSocket connections.", }, func() float64 { return float64(expvarIntValue("LiveSessions")) }) ) func init() { Registry.MustRegister(WSConnectionsActive, HTTPRequestsTotal, HTTPRequestDuration, DBQueryDuration) } func ObserveDB(driverName, operation string, started time.Time, err error) { status := "ok" if err != nil { status = "error" } DBQueryDuration.WithLabelValues(driverName, operation, status).Observe(time.Since(started).Seconds()) } func expvarIntValue(name string) int64 { value := expvar.Get(name) if value == nil { return 0 } n, err := strconv.ParseInt(value.String(), 10, 64) if err != nil { return 0 } return n }