-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomponent_text_handler.go
83 lines (67 loc) · 1.54 KB
/
component_text_handler.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package apexlogutils
import (
"fmt"
"io"
"sync"
"time"
"github.com/apex/log"
)
// start time.
var start = time.Now()
// colors.
const (
none = 0
red = 31
green = 32
yellow = 33
blue = 34
gray = 37
)
var colors = [...]int{
log.DebugLevel: gray,
log.InfoLevel: blue,
log.WarnLevel: yellow,
log.ErrorLevel: red,
log.FatalLevel: red,
}
var strings = [...]string{
log.DebugLevel: "DEBUG",
log.InfoLevel: "INFO",
log.WarnLevel: "WARN",
log.ErrorLevel: "ERROR",
log.FatalLevel: "FATAL",
}
const componentFieldName = "component"
// ComponentTextHandler with additional handling of "component" field for identification of sub components
type ComponentTextHandler struct {
mu sync.Mutex
w io.Writer
}
// NewComponentTextHandler builds new handler.
func NewComponentTextHandler(w io.Writer) *ComponentTextHandler {
return &ComponentTextHandler{
w: w,
}
}
// HandleLog implements log.Handler.
func (h *ComponentTextHandler) HandleLog(e *log.Entry) error {
color := colors[e.Level]
level := strings[e.Level]
names := e.Fields.Names()
h.mu.Lock()
defer h.mu.Unlock()
component := e.Fields.Get(componentFieldName)
if component == nil {
component = "global"
}
ts := time.Since(start) / time.Second
_, _ = fmt.Fprintf(h.w, "\033[%dm%6s\033[0m[%04d] \033[1;30m%-10s\033[0m %-25s", color, level, ts, component, e.Message)
for _, name := range names {
if name == componentFieldName {
continue
}
_, _ = fmt.Fprintf(h.w, " \033[%dm%s\033[0m=%v", color, name, e.Fields.Get(name))
}
_, _ = fmt.Fprintln(h.w)
return nil
}