From 507b3bfc1420275231d2b3b339058e597a324af7 Mon Sep 17 00:00:00 2001 From: Peter Turi Date: Mon, 9 Sep 2024 11:19:44 +0200 Subject: [PATCH] fix: panic when no pool elements have been acquired --- pkg/pgxpoolobserver/observer.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/pkg/pgxpoolobserver/observer.go b/pkg/pgxpoolobserver/observer.go index 49ee3bc64..562f7c719 100644 --- a/pkg/pgxpoolobserver/observer.go +++ b/pkg/pgxpoolobserver/observer.go @@ -134,9 +134,16 @@ func ObservePoolMetrics(meter metric.Meter, pool *pgxpool.Pool, additionalAttrib _, err = meter.RegisterCallback(func(_ context.Context, o metric.Observer) error { stat := pool.Stat() - o.ObserveInt64(acquireCountMetric, stat.AcquireCount(), metric.WithAttributes(additionalAttributes...)) - o.ObserveInt64(acquiredDurationMetric, stat.AcquireDuration().Milliseconds(), metric.WithAttributes(additionalAttributes...)) - o.ObserveInt64(avgAcquiredDurationMetric, stat.AcquireDuration().Milliseconds()/stat.AcquireCount(), metric.WithAttributes(additionalAttributes...)) + + acquireCount := stat.AcquireCount() + acquireDurationMS := stat.AcquireDuration().Milliseconds() + + o.ObserveInt64(acquireCountMetric, acquireCount, metric.WithAttributes(additionalAttributes...)) + o.ObserveInt64(acquiredDurationMetric, acquireDurationMS, metric.WithAttributes(additionalAttributes...)) + + if acquireCount > 0 { + o.ObserveInt64(avgAcquiredDurationMetric, acquireDurationMS/acquireCount, metric.WithAttributes(additionalAttributes...)) + } o.ObserveInt64(acquiredConnsMetric, int64(stat.AcquiredConns()), metric.WithAttributes(additionalAttributes...)) o.ObserveInt64(canceledAcquireCountMetric, stat.CanceledAcquireCount(), metric.WithAttributes(additionalAttributes...)) o.ObserveInt64(constructingConnsMetric, int64(stat.ConstructingConns()), metric.WithAttributes(additionalAttributes...))