-
Notifications
You must be signed in to change notification settings - Fork 12
/
dbstats_go1.11.go
48 lines (43 loc) · 1.16 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
// Copyright 2021 The searKing Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package otlpsql
import (
"context"
"database/sql"
"sync"
"time"
)
// 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()
MeasureOpenConnections.Record(ctx, int64(dbStats.OpenConnections))
MeasureIdleConnections.Record(ctx, int64(dbStats.Idle))
MeasureActiveConnections.Record(ctx, int64(dbStats.InUse))
MeasureWaitCount.Record(ctx, dbStats.WaitCount)
MeasureWaitDuration.Record(ctx, dbStats.WaitDuration.Milliseconds())
MeasureIdleClosed.Record(ctx, dbStats.MaxIdleClosed)
MeasureLifetimeClosed.Record(ctx, dbStats.MaxLifetimeClosed)
case <-done:
ticker.Stop()
return
}
}
}()
return func() {
closeOnce.Do(func() {
close(done)
})
}
}