package metrics import ( "strconv" "time" "github.com/gin-gonic/gin" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" ) var ( HTTPRequestsTotal = promauto.NewCounterVec( prometheus.CounterOpts{Name: "http_requests_total", Help: "Total HTTP requests."}, []string{"method", "path", "status"}, ) HTTPRequestDuration = promauto.NewHistogramVec( prometheus.HistogramOpts{Name: "http_request_duration_seconds", Help: "HTTP request latency.", Buckets: prometheus.DefBuckets}, []string{"method", "path", "status"}, ) ReminderSendTotal = promauto.NewCounterVec( prometheus.CounterOpts{Name: "reminder_send_total", Help: "Reminder delivery results."}, []string{"status"}, ) ReminderRetryTotal = promauto.NewCounter( prometheus.CounterOpts{Name: "reminder_retry_total", Help: "Reminder retry count."}, ) DBQueryDuration = promauto.NewHistogramVec( prometheus.HistogramOpts{Name: "db_query_duration_seconds", Help: "DB query duration.", Buckets: prometheus.DefBuckets}, []string{"op", "table", "success"}, ) ) func init() { ReminderSendTotal.WithLabelValues("sent").Add(0) ReminderSendTotal.WithLabelValues("failed").Add(0) ReminderRetryTotal.Add(0) DBQueryDuration.WithLabelValues("scan_pending", "reminders", "true").Observe(0) } func ObserveHTTP(c *gin.Context, start time.Time) { path := c.FullPath() if path == "" { path = c.Request.URL.Path } status := strconv.Itoa(c.Writer.Status()) labels := []string{c.Request.Method, path, status} HTTPRequestsTotal.WithLabelValues(labels...).Inc() HTTPRequestDuration.WithLabelValues(labels...).Observe(time.Since(start).Seconds()) } func ObserveDB(op, table string, success bool, dur time.Duration) { if table == "" { table = "unknown" } s := "false" if success { s = "true" } DBQueryDuration.WithLabelValues(op, table, s).Observe(dur.Seconds()) }