forked from mtusi2026/mtusi2026lab6
feat: add OpenTelemetry instrumentation
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
var (
|
||||
connectionStateUsed = attribute.String("state", "used")
|
||||
connectionStateIdle = attribute.String("state", "idle")
|
||||
connectionStateConnecting = attribute.String("state", "connecting")
|
||||
)
|
||||
|
||||
func ObserveDatabasePool(meter metric.Meter, pool *pgxpool.Pool) error {
|
||||
_, err := meter.Int64ObservableGauge("messenger_db_pool_connections",
|
||||
metric.WithDescription("PostgreSQL pool connections by state."),
|
||||
metric.WithInt64Callback(func(_ context.Context, observer metric.Int64Observer) error {
|
||||
stats := pool.Stat()
|
||||
observer.Observe(int64(stats.AcquiredConns()), metric.WithAttributes(connectionStateUsed))
|
||||
observer.Observe(int64(stats.IdleConns()), metric.WithAttributes(connectionStateIdle))
|
||||
observer.Observe(int64(stats.ConstructingConns()), metric.WithAttributes(connectionStateConnecting))
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = meter.Int64ObservableCounter("messenger_db_pool_waited",
|
||||
metric.WithDescription("Connection acquisitions that waited because the PostgreSQL pool was empty."),
|
||||
metric.WithInt64Callback(func(_ context.Context, observer metric.Int64Observer) error {
|
||||
observer.Observe(pool.Stat().EmptyAcquireCount())
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user