-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimpleHandler.go
75 lines (58 loc) · 1.33 KB
/
simpleHandler.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
// Package text implements a development-friendly textual handler.
package log
import (
"fmt"
"io"
"sort"
"sync"
"time"
)
// start time.
var shstart = time.Now()
// Strings mapping.
var Strings = [...]string{
DebugLevel: "DEBUG",
InfoLevel: "INFO",
WarnLevel: "WARN",
ErrorLevel: "ERROR",
FatalLevel: "FATAL",
}
// field used for sorting.
type shfield struct {
Name string
Value interface{}
}
// by sorts projects by call count.
type byName []shfield
func (a byName) Len() int { return len(a) }
func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byName) Less(i, j int) bool { return a[i].Name < a[j].Name }
// Handler implementation.
type SimpleHandler struct {
mu sync.Mutex
Writer io.Writer
}
// New handler.
func NewSimple(w io.Writer) Handler {
return &SimpleHandler{
Writer: w,
}
}
// HandleLog implements log.Handler.
func (h *SimpleHandler) HandleLog(e *Entry) error {
level := Strings[e.Level]
var fields []shfield
for k, v := range e.Fields {
fields = append(fields, shfield{k, v})
}
sort.Sort(byName(fields))
h.mu.Lock()
defer h.mu.Unlock()
ts := time.Since(shstart) / time.Second
fmt.Fprintf(h.Writer, "%6s[%04d] %-25s", level, ts, e.Message)
for _, f := range fields {
fmt.Fprintf(h.Writer, " %s=%v", f.Name, f.Value)
}
fmt.Fprintln(h.Writer)
return nil
}