-
Notifications
You must be signed in to change notification settings - Fork 298
/
prefixed_logger.go
57 lines (42 loc) · 1.2 KB
/
prefixed_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
package logger
import (
"strings"
)
// sticks "prefix" at the start of every new line
type prefixedLogger struct {
Logger
original Logger
prefix string
indentBeforeNextWrite bool
}
var _ Logger = &prefixedLogger{}
func NewPrefixedLogger(prefix string, original Logger) *prefixedLogger {
result := &prefixedLogger{original: original, prefix: prefix, indentBeforeNextWrite: true}
delegate := NewFuncLogger(original.SupportsColor(), original.Level(), result.handleLog)
result.Logger = delegate
return result
}
func (i *prefixedLogger) handleLog(level Level, fields Fields, buf []byte) error {
output := ""
if i.indentBeforeNextWrite {
output += i.prefix
}
output += string(buf)
// temporarily take off a trailing newline so that Replace doesn't add a prefix at the end
endsInNewline := false
if len(output) > 0 {
endsInNewline = output[len(output)-1] == '\n'
}
if endsInNewline {
output = output[:len(output)-1]
}
output = strings.ReplaceAll(output, "\n", "\n"+i.prefix)
if endsInNewline {
output += "\n"
i.indentBeforeNextWrite = true
} else {
i.indentBeforeNextWrite = false
}
i.original.WithFields(fields).Write(level, []byte(output))
return nil
}