-
Notifications
You must be signed in to change notification settings - Fork 0
/
timewriter.go
62 lines (52 loc) · 1.06 KB
/
timewriter.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
// A wrapper over io.Writer to begin each line with a timestamp
package timewriter
import (
"fmt"
"io"
"time"
)
// A Writer that begins each line with a timestamp
type TimeWriter struct {
w io.Writer
}
func New(w io.Writer) (*TimeWriter, error) {
// Begin the log with a timestamp
now := []byte(fmt.Sprintf("%s: ", time.Now().UTC().String()))
if _, err := w.Write(now); err != nil {
return nil, err
}
return &TimeWriter{w}, nil
}
func (l *TimeWriter) Write(p []byte) (n int, err error) {
now := []byte(fmt.Sprintf("%s: ", time.Now().UTC().String()))
i := 0
// Flush to w on newline and append a timestamp
for j, b := range p {
if b == '\r' || b == '\n' {
if b == '\r' {
if j+1 < len(p) && p[j+1] == '\n' {
continue
}
}
w, err := l.w.Write(p[i : j+1])
n += w
i = j + 1
if err != nil {
return n, err
}
_, err = l.w.Write(now)
if err != nil {
return n, err
}
}
}
// Write remainder to w
if i != len(p) {
w, err := l.w.Write(p[i:len(p)])
n += w
if err != nil {
return n, err
}
}
return n, nil
}