-
Notifications
You must be signed in to change notification settings - Fork 0
/
timestamp.go
63 lines (59 loc) · 1.34 KB
/
timestamp.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
package main
import (
"bufio"
"fmt"
"io"
"time"
)
const resetColor = "\033[0m"
const warningColor = "\033[33m"
const errorColor = "\033[31m"
// Neatly show a duration in hours, mins, seconds and microseconds.
func niceDuration(d time.Duration) string {
return fmt.Sprintf("%02d:%02d:%02d.%06d",
int(d.Hours()),
int(d.Minutes())%60,
int(d.Seconds())%60,
d.Microseconds()%1000000,
)
}
func timestamp(clock Time, r io.Reader, w io.Writer, wantsColors bool) {
scanner := bufio.NewScanner(r)
startTime := clock.Now()
lastLine := startTime
for scanner.Scan() {
nowTime := clock.Now()
sinceStart := nowTime.Sub(startTime)
sinceLastLine := nowTime.Sub(lastLine)
color := ""
reset := ""
if wantsColors {
if sinceLastLine.Milliseconds() > int64(ErrorAfter) {
color = errorColor
reset = resetColor
} else if sinceLastLine.Milliseconds() > int64(WarnAfter) {
color = warningColor
reset = resetColor
}
}
lineDate := ""
if WantsDateStamp {
lineDate = nowTime.Format("2006-01-02 ")
}
lineTime := ""
if WantsTimeStamp {
lineTime = nowTime.Format("15:04:05.000000 ")
}
fmt.Fprintf(w, "%s%s%s %s%s%s %s\n",
lineDate, lineTime,
niceDuration(sinceStart),
color,
niceDuration(sinceLastLine),
reset,
scanner.Text())
lastLine = nowTime
}
if err := scanner.Err(); err != nil {
panic(err)
}
}