-
Notifications
You must be signed in to change notification settings - Fork 0
/
text_writer.go
86 lines (70 loc) · 1.65 KB
/
text_writer.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
package log
import (
"fmt"
"io"
"strings"
"sync"
"time"
"github.com/fatih/color"
)
type TextWriter struct {
sync.Mutex
IOWriter io.Writer
ErrorIOWriter io.Writer
}
func newTextWriter(w ...io.Writer) Writer {
switch len(w) {
case 1:
return &TextWriter{IOWriter: w[0], ErrorIOWriter: w[0]}
case 2:
return &TextWriter{IOWriter: w[0], ErrorIOWriter: w[1]}
default:
return &TextWriter{IOWriter: color.Output, ErrorIOWriter: color.Error}
}
}
func (w *TextWriter) WriteLog(p *Payload) {
var writer io.Writer
if len(p.Errors) > 0 {
writer = w.ErrorIOWriter
} else {
writer = w.IOWriter
}
w.Lock()
defer w.Unlock()
writeMessage(writer, p)
writeFields(writer, p)
writeTags(writer, p)
fmt.Fprintln(writer)
writeErrors(writer, p)
}
func writeErrors(w io.Writer, p *Payload) {
attr := Colors[p.Level]
level := color.New(attr)
for _, msg := range p.Errors {
level.Fprintln(w, "%6s\033[0m[%04d] %-25s", strings.ToUpper(LevelNames[p.Level]), p.ElapsedSinceStart, msg)
}
}
func writeTags(w io.Writer, p *Payload) {
attr := Colors[p.Level]
level := color.New(attr)
if len(p.Tags) > 0 {
for k, v := range p.Tags {
level.Fprintf(w, " %s|%s\033[0m", k, v)
}
}
}
func writeFields(w io.Writer, p *Payload) {
attr := Colors[p.Level]
level := color.New(attr)
for k, v := range p.Fields {
level.Fprintf(w, " %s\033[0m=%v", k, v)
}
}
func writeMessage(w io.Writer, p *Payload) {
attr := Colors[p.Level]
level := color.New(attr)
for _, msg := range p.Messages {
level.Fprintf(w, "%6s", strings.ToUpper(LevelNames[p.Level]))
fmt.Fprintf(w, "[%04d](%-25s) %-25s", p.ElapsedSinceStart, p.Timestamp.Format(time.RFC3339Nano), msg)
}
}