...
1
16
17 package logreduction
18
19 import (
20 "sync"
21 "time"
22 )
23
24 var nowfunc = func() time.Time { return time.Now() }
25
26
27
28
29
30 type LogReduction struct {
31 lastError map[string]string
32 errorPrinted map[string]time.Time
33 errorMapLock sync.Mutex
34 identicalErrorDelay time.Duration
35 }
36
37
38 func NewLogReduction(identicalErrorDelay time.Duration) *LogReduction {
39 l := new(LogReduction)
40 l.lastError = make(map[string]string)
41 l.errorPrinted = make(map[string]time.Time)
42 l.identicalErrorDelay = identicalErrorDelay
43 return l
44 }
45
46 func (l *LogReduction) cleanupErrorTimeouts() {
47 for name, timeout := range l.errorPrinted {
48 if nowfunc().Sub(timeout) >= l.identicalErrorDelay {
49 delete(l.errorPrinted, name)
50 delete(l.lastError, name)
51 }
52 }
53 }
54
55
56
57 func (l *LogReduction) ShouldMessageBePrinted(message string, parentID string) bool {
58 l.errorMapLock.Lock()
59 defer l.errorMapLock.Unlock()
60 l.cleanupErrorTimeouts()
61 lastMsg, ok := l.lastError[parentID]
62 lastPrinted, ok1 := l.errorPrinted[parentID]
63 if !ok || !ok1 || message != lastMsg || nowfunc().Sub(lastPrinted) >= l.identicalErrorDelay {
64 l.errorPrinted[parentID] = nowfunc()
65 l.lastError[parentID] = message
66 return true
67 }
68 return false
69 }
70
71
72
73 func (l *LogReduction) ClearID(parentID string) {
74 l.errorMapLock.Lock()
75 defer l.errorMapLock.Unlock()
76 delete(l.lastError, parentID)
77 delete(l.errorPrinted, parentID)
78 }
79
View as plain text