-
Notifications
You must be signed in to change notification settings - Fork 314
/
error_map.go
92 lines (79 loc) · 1.46 KB
/
error_map.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"sort"
"strconv"
"sync"
"sync/atomic"
)
type errorMap struct {
mu sync.RWMutex
m map[string]*uint64
}
func newErrorMap() *errorMap {
em := new(errorMap)
em.m = make(map[string]*uint64)
return em
}
func (e *errorMap) add(err error) {
s := err.Error()
e.mu.RLock()
c, ok := e.m[s]
e.mu.RUnlock()
if !ok {
e.mu.Lock()
c, ok = e.m[s]
if !ok {
c = new(uint64)
e.m[s] = c
}
e.mu.Unlock()
}
atomic.AddUint64(c, 1)
}
func (e *errorMap) get(err error) uint64 {
s := err.Error()
e.mu.RLock()
defer e.mu.RUnlock()
c := e.m[s]
if c == nil {
return uint64(0)
}
return *c
}
func (e *errorMap) sum() uint64 {
e.mu.RLock()
defer e.mu.RUnlock()
sum := uint64(0)
for _, v := range e.m {
sum += *v
}
return sum
}
type errorWithCount struct {
error string
count uint64
}
func (ewc *errorWithCount) String() string {
return "<" + ewc.error + ":" +
strconv.FormatUint(ewc.count, decBase) + ">"
}
type errorsByFrequency []*errorWithCount
func (ebf errorsByFrequency) Len() int {
return len(ebf)
}
func (ebf errorsByFrequency) Less(i, j int) bool {
return ebf[i].count > ebf[j].count
}
func (ebf errorsByFrequency) Swap(i, j int) {
ebf[i], ebf[j] = ebf[j], ebf[i]
}
func (e *errorMap) byFrequency() errorsByFrequency {
e.mu.RLock()
byFreq := make(errorsByFrequency, 0, len(e.m))
for err, count := range e.m {
byFreq = append(byFreq, &errorWithCount{err, *count})
}
e.mu.RUnlock()
sort.Sort(byFreq)
return byFreq
}