Instrument a database¶
Create a DB and wrap each query in Query:
db, err := instrument.NewDB(mp.Meter("checkout"), "orders", instrument.WithDBSystem("postgresql"))
if err != nil {
return err
}
defer db.Close()
err = db.Query(ctx, "get_order", func() error {
return conn.QueryRowContext(ctx, getOrderSQL, id).Scan(&order)
})
Query returns the function's error unchanged. Pass a
semantic-convention value
to WithDBSystem. Without it, the required db.system.name attribute reads other_sql.
The query name becomes the value of db.operation.name, so keep it to a fixed set, such as
"get_order". Never pass raw SQL with interpolated values.
Report the connection pool¶
Map your driver's stats to PoolStats in a function that is cheap to call, because it runs
on every collect. For database/sql:
err := db.RegisterPool(func() instrument.PoolStats {
s := conn.Stats()
return instrument.PoolStats{
MaxOpen: s.MaxOpenConnections,
Open: s.OpenConnections,
InUse: s.InUse,
Idle: s.Idle,
WaitCount: s.WaitCount,
WaitSeconds: s.WaitDuration.Seconds(),
}
})
Close it when the pool goes away¶
Call Close when the pool closes. Until you do, the callback keeps running, and keeps
your *sql.DB alive, for the life of the provider. A process that reopens its pool without
closing the helper leaks one callback per reopen.
Use one name per pool¶
A second RegisterPool on the same DB returns ErrPoolRegistered, and that remains true
after Close, so create a new DB when you reopen a pool.
The check cannot see across DB values. OpenTelemetry sums callbacks that share their
attributes, so two DBs with the same name on one meter would report the sum of their pools,
with no error. Give every pool its own name per meter.
Read the signals¶
| Signal | Query |
|---|---|
| Query rate | the count of db.client.operation.duration |
| Query errors | its count where error.type is present |
| Query latency | its buckets |
| Pool utilisation | db.client.connection.count{state=used} over db.client.connection.max |
| Pool saturation | the rate of phpboyscout.db.client.connection.wait_count |
PoolStats.Open is not emitted on its own, because used plus idle is the same number.
A MaxOpen of 0 means unlimited, as it does in database/sql, so db.client.connection.max
reads 0 for such a pool and a ratio against it means nothing.
Expect the pool names to move¶
Only db.client.operation.duration is a Stable convention. The db.client.connection.*
metrics are still in Development, and a later convention could rename them. When this module
adopts one, the changelog will say so.