-
Notifications
You must be signed in to change notification settings - Fork 3
/
log.go
132 lines (113 loc) · 3.26 KB
/
log.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
//Package antilog is the antidote to modern loggers.
//
// AntiLog only logs JSON formatted output. Structured logging is the only good
// logging.
//
// AntiLog does not have log levels. If you don't want something logged, don't
// log it.
//
// AntiLog does support setting fields in context. Useful for building a log
// context over the course of an operation.
package antilog
import (
"bytes"
"encoding/json"
"io"
"os"
"sync"
"time"
)
// AntiLog is the antidote to modern loggers
type AntiLog struct {
Fields EncodedFields
Writer io.Writer
}
// New instance of AntiLog
func New() AntiLog {
return AntiLog{}
}
// With returns a copy of the AntiLog instance with the provided fields preset for every subsequent call.
func (a AntiLog) With(fields ...Field) AntiLog {
a.Fields = encodeFieldList(fields).PrependUnique(a.Fields)
return a
}
var buffers = sync.Pool{New: func() interface{} { return bytes.NewBuffer(make([]byte, 0, 1024)) }}
// Write a JSON message to the configured writer or os.Stderr.
//
// Includes the message with the key `message`. Includes the timestamp with the
// key `timestamp`. The timestamp field is always first and the message second.
//
// Fields in context will not be overridden. AntiLog will log the same key
// multiple times if it is set multiple times. If you don't want that, don't
// specify it multiple times.
func (a AntiLog) Write(msg string, fields ...Field) {
now := time.Now().UTC()
encodedFields := EncodedFields{}.
PrependUnique(encodeFieldList(fields)).
PrependUnique(a.Fields)
const messageKey, timestampKey = "message", "timestamp"
var lenEncFields int
for _, field := range encodedFields {
key := field.Key()
if key == messageKey || key == timestampKey {
continue
}
lenEncFields += 2 + len(key) + 2 + len(field.Value())
}
const begin, msgInsert = `{ "` + timestampKey + `": "`, `", "` + messageKey + `": `
sb := buffers.Get().(*bytes.Buffer)
sb.Reset()
sb.Grow(len(begin) + len(time.RFC3339) + len(msgInsert) + len(msg) + lenEncFields + 2)
sb.WriteString(begin)
sb.WriteString(now.Format(time.RFC3339))
sb.WriteString(msgInsert)
_ = json.NewEncoder(sb).Encode(msg)
if sb.Bytes()[sb.Len()-1] == '\n' {
sb.Truncate(sb.Len() - 1)
}
for _, field := range encodedFields {
key := field.Key()
if key == "message" || key == "timestamp" {
continue
}
sb.WriteString(", ")
sb.WriteString(key)
sb.WriteString(`: `)
sb.WriteString(field.Value())
}
sb.WriteString(" }\n")
w := a.Writer
if w == nil {
w = os.Stderr
}
_, _ = w.Write(sb.Bytes())
buffers.Put(sb)
}
func toJSON(field Field) string {
// In the case of errors, explicitly destructure them
if err, ok := field.(error); ok {
field = err.Error()
}
// For anything else, just let json.Marshal do it
bytes, err := json.Marshal(field)
if err != nil {
return string(err.Error())
}
return string(bytes)
}
func encodeFieldList(fields []Field) EncodedFields {
convertedFields := make(EncodedFields, 0, len(fields))
numFields := len(fields) / 2
for ix := 0; ix < numFields; ix++ {
rawKey := fields[ix*2]
rawValue := fields[ix*2+1]
keyString, ok := rawKey.(string)
if !ok {
continue
}
key := toJSON(keyString)
value := toJSON(rawValue)
convertedFields = append(convertedFields, EncodedField{key, value})
}
return convertedFields
}