-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
63 lines (54 loc) · 1.03 KB
/
logger.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 (
"fmt"
"io"
"os"
"strings"
"time"
)
type Logger interface {
Printf(string, ...interface{})
}
type logger struct {
Prefixes []string
Timed bool
Writer io.Writer
started time.Time
reader io.ReadCloser
writer io.WriteCloser
c chan error
}
func newLogger(opts ...loggerOpt) *logger {
l := &logger{
started: time.Now(),
Writer: os.Stderr,
}
for _, o := range opts {
o(l)
}
return l
}
type loggerOpt func(*logger)
func timed(o *logger) {
o.Timed = true
}
func (l *logger) Printf(m string, args ...interface{}) {
fmt.Fprint(l.Writer, l.prefix()+fmt.Sprintf(m, args...)+"\n")
}
func (l *logger) prefix() string {
p := []string{}
if l.Timed {
p = append(p, "["+formatTime(time.Since(l.started).Seconds(), 3)+"]")
}
for _, prefix := range l.Prefixes {
p = append(p, "["+prefix+"]")
}
if len(p) == 0 {
return ""
}
return strings.Join(p, "") + " "
}
func formatTime(in float64, digits int) string {
s := fmt.Sprintf("%.03f", in)
return fmt.Sprintf("%*s", digits+1+3, s)
}