-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats.go
67 lines (53 loc) · 1.41 KB
/
stats.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package command
import (
"context"
"sync"
"github.com/sirupsen/logrus"
)
type requestStatsKey struct{}
//nolint:stylecheck // This is unintentionally missing documentation.
type Stats struct {
registry map[string]int
sync.Mutex
}
//nolint:stylecheck // This is unintentionally missing documentation.
func (stats *Stats) RecordSum(key string, value int) {
stats.Lock()
defer stats.Unlock()
if prevValue, ok := stats.registry[key]; ok {
value += prevValue
}
stats.registry[key] = value
}
//nolint:stylecheck // This is unintentionally missing documentation.
func (stats *Stats) RecordMax(key string, value int) {
stats.Lock()
defer stats.Unlock()
if prevValue, ok := stats.registry[key]; ok {
if prevValue > value {
return
}
}
stats.registry[key] = value
}
//nolint:stylecheck // This is unintentionally missing documentation.
func (stats *Stats) Fields() logrus.Fields {
stats.Lock()
defer stats.Unlock()
f := logrus.Fields{}
for k, v := range stats.registry {
f[k] = v
}
return f
}
//nolint:stylecheck // This is unintentionally missing documentation.
func StatsFromContext(ctx context.Context) *Stats {
stats, _ := ctx.Value(requestStatsKey{}).(*Stats)
return stats
}
//nolint:stylecheck // This is unintentionally missing documentation.
func InitContextStats(ctx context.Context) context.Context {
return context.WithValue(ctx, requestStatsKey{}, &Stats{
registry: make(map[string]int),
})
}