metrics.go34 lines, 1.7 KB
| 1 | package postgres |
| 2 | |
| 3 | import ( |
| 4 | "github.com/jackc/pgx/v5/pgxpool" |
| 5 | "github.com/prometheus/client_golang/prometheus" |
| 6 | "github.com/prometheus/client_golang/prometheus/promauto" |
| 7 | ) |
| 8 | |
| 9 | // RegisterMetrics reports pool's statistics to Prometheus, read at every |
| 10 | // scrape, with a pool label: name. Waits that climb mean requests queue for |
| 11 | // a connection, which no query's own timing ever shows. |
| 12 | func RegisterMetrics(name string, pool *pgxpool.Pool) { |
| 13 | labels := prometheus.Labels{"pool": name} |
| 14 | stat := func(f func(*pgxpool.Stat) float64) func() float64 { |
| 15 | return func() float64 { return f(pool.Stat()) } |
| 16 | } |
| 17 | promauto.NewGaugeFunc(prometheus.GaugeOpts{ |
| 18 | Name: "db_pool_max_conns", Help: "The most connections the pool may open.", ConstLabels: labels, |
| 19 | }, stat(func(s *pgxpool.Stat) float64 { return float64(s.MaxConns()) })) |
| 20 | promauto.NewGaugeFunc(prometheus.GaugeOpts{ |
| 21 | Name: "db_pool_acquired_conns", Help: "Connections in use right now.", ConstLabels: labels, |
| 22 | }, stat(func(s *pgxpool.Stat) float64 { return float64(s.AcquiredConns()) })) |
| 23 | promauto.NewCounterFunc(prometheus.CounterOpts{ |
| 24 | Name: "db_pool_acquires_total", Help: "Connections handed out.", ConstLabels: labels, |
| 25 | }, stat(func(s *pgxpool.Stat) float64 { return float64(s.AcquireCount()) })) |
| 26 | promauto.NewCounterFunc(prometheus.CounterOpts{ |
| 27 | Name: "db_pool_waits_total", Help: "Acquires that waited: every connection was busy.", |
| 28 | ConstLabels: labels, |
| 29 | }, stat(func(s *pgxpool.Stat) float64 { return float64(s.EmptyAcquireCount()) })) |
| 30 | promauto.NewCounterFunc(prometheus.CounterOpts{ |
| 31 | Name: "db_pool_wait_seconds_total", Help: "Time spent waiting for a connection.", |
| 32 | ConstLabels: labels, |
| 33 | }, stat(func(s *pgxpool.Stat) float64 { return s.EmptyAcquireWaitTime().Seconds() })) |
| 34 | } |