forked from TheThingsArchive/ttn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log_handler.go
98 lines (76 loc) · 1.7 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
92
93
94
95
96
97
98
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
package testing
import (
"bytes"
"sort"
"sync"
"testing"
"fmt"
"github.com/apex/log"
)
// colors.
const (
none = 0
red = 31
green = 32
yellow = 33
blue = 34
gray = 90
)
// 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",
}
// field used for sorting.
type field struct {
Name string
Value interface{}
}
// by sorts projects by call count.
type byName []field
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 }
// LogHandler implementation.
type LogHandler struct {
mu sync.Mutex
T *testing.T
}
// NewLogHandler handler.
func NewLogHandler(t *testing.T) *LogHandler {
return &LogHandler{
T: t,
}
}
// HandleLog implements log.Handler.
func (h *LogHandler) HandleLog(e *log.Entry) error {
color := Colors[e.Level]
level := Strings[e.Level]
var fields []field
for k, v := range e.Fields {
fields = append(fields, field{k, v})
}
sort.Sort(byName(fields))
h.mu.Lock()
defer h.mu.Unlock()
buf := bytes.NewBuffer([]byte{})
fmt.Fprintf(buf, "\033[%dm%6s\033[0m %-25s", color, level, e.Message)
for _, f := range fields {
fmt.Fprintf(buf, " \033[%dm%s\033[0m=%v", color, f.Name, f.Value)
}
h.T.Log(buf.String())
return nil
}