-
Notifications
You must be signed in to change notification settings - Fork 27
/
dbstats_go1.11.go
50 lines (44 loc) · 1.02 KB
/
dbstats_go1.11.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// +build go1.11
package ocsql
import (
"context"
"database/sql"
"sync"
"time"
"go.opencensus.io/stats"
)
// RecordStats records database statistics for provided sql.DB at the provided
// interval.
func RecordStats(db *sql.DB, interval time.Duration) (fnStop func()) {
var (
closeOnce sync.Once
ctx = context.Background()
ticker = time.NewTicker(interval)
done = make(chan struct{})
)
go func() {
for {
select {
case <-ticker.C:
dbStats := db.Stats()
stats.Record(ctx,
MeasureOpenConnections.M(int64(dbStats.OpenConnections)),
MeasureIdleConnections.M(int64(dbStats.Idle)),
MeasureActiveConnections.M(int64(dbStats.InUse)),
MeasureWaitCount.M(dbStats.WaitCount),
MeasureWaitDuration.M(float64(dbStats.WaitDuration.Nanoseconds())/1e6),
MeasureIdleClosed.M(dbStats.MaxIdleClosed),
MeasureLifetimeClosed.M(dbStats.MaxLifetimeClosed),
)
case <-done:
ticker.Stop()
return
}
}
}()
return func() {
closeOnce.Do(func() {
close(done)
})
}
}