-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_target.go
103 lines (90 loc) · 2.37 KB
/
json_target.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
99
100
101
102
103
package blackbox
import (
"encoding/json"
"fmt"
"io"
"strings"
"time"
)
// NewJSONTarget creates a JSONTarget for use with a logger
func NewJSONTarget(outTarget io.Writer, errTarget io.Writer) *JSONTarget {
return &JSONTarget{
outTarget: outTarget,
errTarget: errTarget,
level: Trace,
showTimestamp: true,
showLevel: true,
showContext: true,
}
}
// JSONTarget is a Target that produces newline separated json output containing
// log data.
type JSONTarget struct {
outTarget io.Writer
errTarget io.Writer
level Level
showTimestamp bool
showLevel bool
showContext bool
}
// SetLevel sets the minimum log level that JSONTarget will output. Note that
// this setting is independent of the log level set on the logger itself.
func (j *JSONTarget) SetLevel(level Level) *JSONTarget {
j.level = level
return j
}
// ShowTimestamp will enable or disable timestamps in the output depending on
// the boolean value passed.
func (j *JSONTarget) ShowTimestamp(b bool) *JSONTarget {
j.showTimestamp = b
return j
}
// ShowLevel will enable or disable level values in the output depending on
// the boolean value passed.
func (j *JSONTarget) ShowLevel(b bool) *JSONTarget {
j.showLevel = b
return j
}
// ShowContext will enable or disable context key value pairs in the output
// depending on the boolean value passed.
func (j *JSONTarget) ShowContext(b bool) *JSONTarget {
j.showContext = b
return j
}
// Log takes a Level and series of values, then outputs them formatted
// accordingly.
func (j *JSONTarget) Log(level Level, values []interface{}, context Ctx) {
if level < j.level {
return
}
jsonData := make(map[string]interface{}, 1)
if j.showTimestamp {
jsonData["time"] = time.Now().Local().Format(time.RFC3339)
}
if j.showLevel {
jsonData["level"] = level.String()
}
strValues := make([]string, 0)
for _, value := range values {
strValues = append(strValues, fmt.Sprintf("%+v", value))
}
fmt.Printf("%+v\n", values)
fmt.Printf("%+v\n", strValues)
jsonData["message"] = strings.Join(strValues, " ")
if j.showContext {
jsonData["context"] = context
}
jsonBytes, err := json.Marshal(jsonData)
if err != nil {
panic(err)
}
jsonBytes = []byte(string(jsonBytes) + "\n")
if level >= Warn {
_, err = j.errTarget.Write(jsonBytes)
} else {
_, err = j.outTarget.Write(jsonBytes)
}
if err != nil {
panic(err)
}
}