forked from anycable/anycable-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log_handler.go
91 lines (72 loc) · 1.57 KB
/
log_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
84
85
86
87
88
89
90
91
package utils
import (
"fmt"
"io"
"sync"
"time"
"github.com/apex/log"
)
// colors.
const (
red = 31
yellow = 33
blue = 34
gray = 37
)
// Colors mapping.
var Colors = [...]int{
log.DebugLevel: gray,
log.InfoLevel: blue,
log.WarnLevel: yellow,
log.ErrorLevel: red,
log.FatalLevel: red,
}
// Strings mapping.
var Strings = [...]string{
log.DebugLevel: "DEBUG",
log.InfoLevel: "INFO",
log.WarnLevel: "WARN",
log.ErrorLevel: "ERROR",
log.FatalLevel: "FATAL",
}
// Chars mapping.
var Chars = [...]string{
log.DebugLevel: "D",
log.InfoLevel: "I",
log.WarnLevel: "W",
log.ErrorLevel: "E",
log.FatalLevel: "F",
}
// LogHandler with TTY awareness
type LogHandler struct {
mu sync.Mutex
writer io.Writer
tty bool
}
const (
timeFormat = "2006-01-02T15:04:05.000Z"
)
// HandleLog is a method called by logger to record a log entry
func (h *LogHandler) HandleLog(e *log.Entry) error {
names := e.Fields.Names()
ts := time.Now().UTC().Format(timeFormat)
h.mu.Lock()
defer h.mu.Unlock()
if h.tty {
color := Colors[e.Level]
level := Strings[e.Level]
fmt.Fprintf(h.writer, "\033[%dm%6s\033[0m %s", color, level, ts)
for _, name := range names {
fmt.Fprintf(h.writer, " \033[%dm%s\033[0m=%v", color, name, e.Fields.Get(name))
}
fmt.Fprintf(h.writer, " \033[%dm%-25s\033[0m\n", color, e.Message)
} else {
level := Chars[e.Level]
fmt.Fprintf(h.writer, "%s %s", level, ts)
for _, name := range names {
fmt.Fprintf(h.writer, " %s=%v", name, e.Fields.Get(name))
}
fmt.Fprintf(h.writer, " %-25s\n", e.Message)
}
return nil
}