Go · 751 bytes Raw Blame History
1 // SPDX-License-Identifier: AGPL-3.0-or-later
2
3 package metrics
4
5 import (
6 "context"
7 "time"
8
9 "github.com/jackc/pgx/v5/pgxpool"
10 )
11
12 // ObserveDBPool starts a goroutine that periodically refreshes the pgx
13 // pool gauges. The goroutine exits when ctx is canceled.
14 func ObserveDBPool(ctx context.Context, pool *pgxpool.Pool, interval time.Duration) {
15 if pool == nil {
16 return
17 }
18 if interval <= 0 {
19 interval = 10 * time.Second
20 }
21 go func() {
22 t := time.NewTicker(interval)
23 defer t.Stop()
24 for {
25 select {
26 case <-ctx.Done():
27 return
28 case <-t.C:
29 stat := pool.Stat()
30 DBConnsAcquired.Set(float64(stat.AcquiredConns()))
31 DBConnsIdle.Set(float64(stat.IdleConns()))
32 DBConnsTotal.Set(float64(stat.TotalConns()))
33 }
34 }
35 }()
36 }
37