-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprogress.go
More file actions
108 lines (94 loc) · 1.98 KB
/
progress.go
File metadata and controls
108 lines (94 loc) · 1.98 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Copyright (c) 2018-2019 KIDTSUNAMI
// Author: alex@kidtsunami.com
package log
import (
"fmt"
"strings"
"sync"
"time"
)
const defaultProgressInterval = 10 * time.Second
type ProgressLogger struct {
sync.Mutex
action string
event string
interval time.Duration
calls int64
events int64
lastLogTime time.Time
logger Logger
}
func NewProgressLogger(logger Logger) *ProgressLogger {
if logger == nil {
logger = Log
}
return &ProgressLogger{
action: "Processed",
event: "call",
interval: defaultProgressInterval,
lastLogTime: time.Now(),
logger: logger,
}
}
func (l *ProgressLogger) SetAction(action string) *ProgressLogger {
l.action = action
return l
}
func (l *ProgressLogger) SetEvent(event string) *ProgressLogger {
l.event = event
return l
}
func (l *ProgressLogger) SetInterval(interval time.Duration) *ProgressLogger {
l.interval = interval
return l
}
func pluralize(str string, count int64) string {
if count == 0 || count > 1 {
str += "s"
}
return str
}
func (p *ProgressLogger) Log(n int, extra ...string) {
p.Lock()
defer p.Unlock()
p.calls++
p.events += int64(n)
now := time.Now()
duration := now.Sub(p.lastLogTime)
if duration < p.interval || p.events == 0 {
return
}
// Truncate the duration to 10s of milliseconds.
tDuration := duration.Truncate(10 * time.Millisecond)
// Log information about the event.
suffix := ""
if ex := strings.Join(extra, " "); len(ex) > 0 {
suffix = fmt.Sprintf(" (%d %s, %s)", p.calls, pluralize("call", p.calls), ex)
}
p.logger.Infof("%s %d %s in %s"+suffix,
p.action,
p.events,
pluralize(p.event, p.events),
tDuration,
)
p.calls = 0
p.events = 0
p.lastLogTime = now
}
func (p *ProgressLogger) Flush() {
p.Lock()
defer p.Unlock()
if p.calls == 0 {
return
}
now := time.Now()
p.logger.Infof("%s %d %s in %s",
p.action,
p.events,
pluralize(p.event, p.events),
now.Sub(p.lastLogTime),
)
p.calls = 0
p.events = 0
p.lastLogTime = now
}