-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
237 lines (207 loc) · 6.58 KB
/
logger.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package logger
import (
"fmt"
"os"
"reflect"
"time"
)
// Logger is a Logger that creates Bunyan's compatible logs (see: https://github.com/trentm/node-bunyan)
type Logger struct {
stream Streamer
record Record
}
// Must returns the given logger or panics if there is an error or if the Logger is nil
func Must(log *Logger, err error) *Logger {
if err != nil {
panic(err.Error())
} else if log == nil {
panic("Logger is nil")
}
return log
}
// Create creates a new Logger
func Create(name string, parameters ...interface{}) *Logger {
var (
destinations = []string{}
streams = []Streamer{}
records = []Record{}
filterLevel = GetLevelFromEnvironment()
)
for _, parameter := range parameters {
switch parameter := parameter.(type) {
case *Logger:
if parameter != nil {
return parameter
}
case string:
destinations = append(destinations, parameter)
case Level:
filterLevel = parameter
default:
if streamer, ok := parameter.(Streamer); ok {
streams = append(streams, streamer)
} else if record, ok := parameter.(Record); ok {
records = append(records, record)
}
}
// if param is a struct or pointer to struct, or interface
// we should use it for the Topic, Scope
}
for _, destination := range destinations {
streams = append(streams, CreateStreamWithDestination(destination).SetFilterLevel(filterLevel))
}
logger := CreateWithStream(name, streams...)
if len(records) > 0 {
for _, record := range records {
for key, value := range record {
logger.record.Set(key, value)
}
}
}
return logger
}
// CreateWithDestination creates a new Logger streaming to the given destination(s)
func CreateWithDestination(name string, destinations ...string) *Logger {
return CreateWithStream(name, CreateStreamWithDestination(destinations...))
}
// CreateWithStream creates a new Logger streaming to the given stream or list of streams
func CreateWithStream(name string, streams ...Streamer) *Logger {
hostname, _ := os.Hostname()
record := NewRecord().
Set("name", name).
Set("hostname", hostname).
Set("pid", os.Getpid()).
Set("tid", func() interface{} { return gettid() }).
Set("topic", "main").
Set("scope", "main").
Set("v", 0)
if len(streams) == 0 {
return &Logger{CreateStreamWithDestination(), record}
} else if len(streams) == 1 {
return &Logger{streams[0], record}
}
return &Logger{&MultiStream{streams: streams}, record}
}
// CreateIfNil creates a new Logger if the given Logger is nil, otherwise return the said Logger
func CreateIfNil(logger *Logger, name string) *Logger {
if logger != nil {
return logger
}
return CreateWithStream(name, &NilStream{})
}
// Close closes the logger's stream
func (log *Logger) Close() {
log.stream.Close()
}
// Record adds the given Record to the Log
func (log *Logger) Record(key string, value interface{}) *Logger {
// This func requires Logger to be a Stream
// that allows us to nest Loggers
return &Logger{log, NewRecord().Set(key, value)}
}
// Recordf adds the given Record with formatted arguments
func (log *Logger) Recordf(key, value string, args ...interface{}) *Logger {
return log.Record(key, fmt.Sprintf(value, args...))
}
// Records adds key, value pairs as Record objects
// E.g.: log.Records("key1", value1, "key2", value2)
// The key should be castable to a string
// If the last value is missing, its key is ignored
func (log *Logger) Records(params ...interface{}) *Logger {
if len(params) == 0 {
return log
}
var key string
record := NewRecord()
for i, param := range params {
if i%2 == 0 {
key = param.(string)
} else if len(key) > 0 {
record.Set(key, param)
}
}
return &Logger{log, record}
}
// Topic sets the Topic of this Logger
func (log *Logger) Topic(value interface{}) *Logger {
return log.Record("topic", value)
}
// Scope sets the Scope if this Logger
func (log *Logger) Scope(value interface{}) *Logger {
return log.Record("scope", value)
}
// Child creates a child Logger with a topic, a scope, and records
func (log *Logger) Child(topic, scope interface{}, params ...interface{}) *Logger {
var key string
record := NewRecord().Set("topic", topic).Set("scope", scope)
for i, param := range params {
if i%2 == 0 {
key = param.(string)
} else if len(key) > 0 {
record.Set(key, param)
}
}
return &Logger{log, record}
}
// GetRecord returns the Record field value for a given key
func (log *Logger) GetRecord(key string) interface{} {
value := log.record[key]
if value != nil {
return value
}
// TODO: find a way to traverse the parent Stream/Logger objects
return nil
}
// String gets a string version
// implements the fmt.Stringer interface
func (log Logger) String() string {
return fmt.Sprintf("Logger(%s)", log.stream)
}
// Tracef traces a message at the TRACE Level
func (log *Logger) Tracef(msg string, args ...interface{}) { log.send(TRACE, msg, args...) }
// Debugf traces a message at the DEBUG Level
func (log *Logger) Debugf(msg string, args ...interface{}) { log.send(DEBUG, msg, args...) }
// Infof traces a message at the INFO Level
func (log *Logger) Infof(msg string, args ...interface{}) { log.send(INFO, msg, args...) }
// Warnf traces a message at the WARN Level
func (log *Logger) Warnf(msg string, args ...interface{}) { log.send(WARN, msg, args...) }
// Errorf traces a message at the ERROR Level
// If the last argument is an error, a Record is added and the error string is added to the message
func (log *Logger) Errorf(msg string, args ...interface{}) {
logWithErr := log
if len(args) > 0 {
errorInterface := reflect.TypeOf((*error)(nil)).Elem()
last := args[len(args)-1]
if reflect.TypeOf(last).Implements(errorInterface) {
logWithErr = log.Record("err", last)
msg = msg + ", Error: %+v"
}
}
logWithErr.send(ERROR, msg, args...)
}
// Fatalf traces a message at the FATAL Level
// If the last argument is an error, a Record is added and the error string is added to the message
func (log *Logger) Fatalf(msg string, args ...interface{}) {
logWithErr := log
if len(args) > 0 {
errorInterface := reflect.TypeOf((*error)(nil)).Elem()
last := args[len(args)-1]
if reflect.TypeOf(last).Implements(errorInterface) {
logWithErr = log.Record("err", last)
msg = msg + ", Error: %+v"
}
}
logWithErr.send(FATAL, msg, args...)
}
// send writes a message to the Sink
func (log *Logger) send(level Level, msg string, args ...interface{}) {
if log.ShouldWrite(level) {
record := NewRecord()
record["time"] = time.Now().UTC()
record["level"] = level
record["msg"] = fmt.Sprintf(msg, args...)
if err := log.Write(record); err != nil {
fmt.Fprintf(os.Stderr, "Logger error: %s\n", err)
}
}
}