/
logger.go
413 lines (353 loc) · 11.2 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package logger
import (
"io"
"log"
"os"
"strings"
"sync"
kv "gopkg.in/Clever/kayvee-go.v6"
"gopkg.in/Clever/kayvee-go.v6/router"
)
/////////////////////
//
// Helper definitions
//
/////////////////////
// Formatter is a function type that takes a map and returns a formatted string with the contents of the map
type Formatter func(data map[string]interface{}) string
// M is a convenience type for passing data into a log message.
type M map[string]interface{}
// LogLevel is an enum is used to denote level of logging
type LogLevel int
// Constants used to define different LogLevels supported
const (
Trace LogLevel = iota
Debug
Info
Warning
Error
Critical
)
var logLevelNames = map[LogLevel]string{
Trace: "trace",
Debug: "debug",
Info: "info",
Warning: "warning",
Error: "error",
Critical: "critical",
}
func (l LogLevel) String() string {
switch l {
case Trace:
fallthrough
case Debug:
fallthrough
case Info:
fallthrough
case Warning:
fallthrough
case Error:
fallthrough
case Critical:
return logLevelNames[l]
}
return ""
}
/////////////////////////////
//
// Logger
//
/////////////////////////////
// Logger is the default implementation of KayveeLogger.
// It provides customization of globals, default log level, formatting, and output destination.
type Logger struct {
globalsL sync.RWMutex
globals map[string]interface{}
logLvl LogLevel
fLogger formatLogger
logRouter router.Router
}
var globalRouter router.Router
var reservedKeyNames = map[string]bool{
"title": true,
"source": true,
"value": true,
"type": true,
"level": true,
"_kvmeta": true,
}
// SetGlobalRouting installs a new log router onto the KayveeLogger with the
// configuration specified in `filename`. For convenience, the KayveeLogger is expected
// to return itself as the first return value.
func SetGlobalRouting(filename string) error {
var err error
globalRouter, err = router.NewFromConfig(filename)
return err
}
// SetGlobalRoutingFromBytes installs a new log router onto the KayveeLogger with the
// configuration specified in . For convenience, the KayveeLogger is expected
// to return itself as the first return value.
func SetGlobalRoutingFromBytes(fileBytes []byte) error {
var err error
globalRouter, err = router.NewFromConfigBytes(fileBytes)
return err
}
// SetConfig implements the method for the KayveeLogger interface.
func (l *Logger) SetConfig(source string, logLvl LogLevel, formatter Formatter, output io.Writer) {
l.globalsL.Lock()
defer l.globalsL.Unlock()
if l.globals == nil {
l.globals = make(map[string]interface{})
}
l.globals["source"] = source
l.logLvl = logLvl
l.fLogger.setFormatter(formatter)
l.fLogger.setOutput(output)
}
// AddContext implements the method for the KayveeLogger interface.
func (l *Logger) AddContext(key, val string) {
l.globalsL.Lock()
defer l.globalsL.Unlock()
updateContextMapIfNotReserved(l.globals, key, val)
}
// GetContext implements the method for the KayveeLogger interface.
func (l *Logger) GetContext(key string) (interface{}, bool) {
l.globalsL.RLock()
defer l.globalsL.RUnlock()
val, ok := l.globals[key]
return val, ok
}
// SetRouter implements the method for the KayveeLogger interface.
func (l *Logger) SetRouter(router router.Router) {
l.logRouter = router
}
// SetLogLevel implements the method for the KayveeLogger interface.
func (l *Logger) SetLogLevel(logLvl LogLevel) {
l.logLvl = logLvl
}
// SetFormatter implements the method for the KayveeLogger interface.
func (l *Logger) SetFormatter(formatter Formatter) {
l.fLogger.setFormatter(formatter)
}
// SetOutput implements the method for the KayveeLogger interface.
func (l *Logger) SetOutput(output io.Writer) {
l.fLogger.setOutput(output)
}
func (l *Logger) setFormatLogger(fl formatLogger) {
l.fLogger = fl
}
// Trace implements the method for the KayveeLogger interface.
func (l *Logger) Trace(title string) {
l.TraceD(title, M{})
}
// Debug implements the method for the KayveeLogger interface.
func (l *Logger) Debug(title string) {
l.DebugD(title, M{})
}
// Info implements the method for the KayveeLogger interface.
func (l *Logger) Info(title string) {
l.InfoD(title, M{})
}
// Warn implements the method for the KayveeLogger interface.
func (l *Logger) Warn(title string) {
l.WarnD(title, M{})
}
// Error implements the method for the KayveeLogger interface.
func (l *Logger) Error(title string) {
l.ErrorD(title, M{})
}
// Critical implements the method for the KayveeLogger interface.
func (l *Logger) Critical(title string) {
l.CriticalD(title, M{})
}
// Counter implements the method for the KayveeLogger interface.
// Logs with type = gauge, and value = value
func (l *Logger) Counter(title string) {
l.CounterD(title, 1, M{}) // Defaults to a value of 1
}
// GaugeInt implements the method for the KayveeLogger interface.
// Logs with type = gauge, and value = value
func (l *Logger) GaugeInt(title string, value int) {
l.GaugeIntD(title, value, M{})
}
// GaugeFloat implements the method for the KayveeLogger interface.
// Logs with type = gauge, and value = value
func (l *Logger) GaugeFloat(title string, value float64) {
l.GaugeFloatD(title, value, M{})
}
// TraceD implements the method for the KayveeLogger interface.
func (l *Logger) TraceD(title string, data map[string]interface{}) {
data["title"] = title
l.logWithLevel(Trace, data)
}
// DebugD implements the method for the KayveeLogger interface.
func (l *Logger) DebugD(title string, data map[string]interface{}) {
data["title"] = title
l.logWithLevel(Debug, data)
}
// InfoD implements the method for the KayveeLogger interface.
func (l *Logger) InfoD(title string, data map[string]interface{}) {
data["title"] = title
l.logWithLevel(Info, data)
}
// WarnD implements the method for the KayveeLogger interface.
func (l *Logger) WarnD(title string, data map[string]interface{}) {
data["title"] = title
l.logWithLevel(Warning, data)
}
// ErrorD implements the method for the KayveeLogger interface.
func (l *Logger) ErrorD(title string, data map[string]interface{}) {
data["title"] = title
l.logWithLevel(Error, data)
}
// CriticalD implements the method for the KayveeLogger interface.
func (l *Logger) CriticalD(title string, data map[string]interface{}) {
data["title"] = title
l.logWithLevel(Critical, data)
}
// CounterD implements the method for the KayveeLogger interface.
// Logs with type = gauge, and value = value
func (l *Logger) CounterD(title string, value int, data map[string]interface{}) {
data["title"] = title
data["value"] = value
data["type"] = "counter"
l.logWithLevel(Info, data)
}
// GaugeIntD implements the method for the KayveeLogger interface.
// Logs with type = gauge, and value = value
func (l *Logger) GaugeIntD(title string, value int, data map[string]interface{}) {
l.gauge(title, value, data)
}
// GaugeFloatD implements the method for the KayveeLogger interface.
// Logs with type = gauge, and value = value
func (l *Logger) GaugeFloatD(title string, value float64, data map[string]interface{}) {
l.gauge(title, value, data)
}
func (l *Logger) gauge(title string, value interface{}, data map[string]interface{}) {
data["title"] = title
data["value"] = value
data["type"] = "gauge"
l.logWithLevel(Info, data)
}
// Actual logging. Handles whether to output based on log level and
// unifies the passed in data with the stored globals
func (l *Logger) logWithLevel(logLvl LogLevel, data map[string]interface{}) {
if logLvl < l.logLvl {
// No log output
return
}
data["level"] = logLvl.String()
l.globalsL.RLock()
defer l.globalsL.RUnlock()
for key, value := range l.globals {
if _, ok := data[key]; ok {
// Values in the data map override the globals
continue
}
data[key] = value
}
if l.logRouter != nil {
data["_kvmeta"] = l.logRouter.Route(data)
} else if globalRouter != nil {
data["_kvmeta"] = globalRouter.Route(data)
}
l.fLogger.formatAndLog(data)
}
// updateContextMapIfNotReserved updates context[key] to val if key is not in the reserved list.
func updateContextMapIfNotReserved(context M, key string, val interface{}) {
if reservedKeyNames[strings.ToLower(key)] {
log.Printf("WARN: kayvee logger reserves '%s' from being set as context", key)
return
}
context[key] = val
}
// New creates a *logger.Logger. Default values are Debug LogLevel, kayvee Formatter, and std.err output.
func New(source string) KayveeLogger {
return NewWithContext(source, nil)
}
// NewWithContext creates a *logger.Logger. Default values are Debug LogLevel, kayvee Formatter, and std.err output.
func NewWithContext(source string, contextValues map[string]interface{}) KayveeLogger {
context := M{}
for k, v := range contextValues {
updateContextMapIfNotReserved(context, k, v)
}
if teamName := os.Getenv("_TEAM_OWNER"); teamName != "" {
context["team"] = teamName
} else if teamName := os.Getenv("TEAM_OWNER"); teamName != "" {
context["team"] = teamName
}
if v := os.Getenv("_DEPLOY_ENV"); v != "" {
context["deploy_env"] = v
} else if v := os.Getenv("DEPLOY_ENV"); v != "" {
context["deploy_env"] = v
}
if os.Getenv("_EXECUTION_NAME") != "" {
context["wf_id"] = os.Getenv("_EXECUTION_NAME")
}
if os.Getenv("_POD_ID") != "" {
context["pod-id"] = os.Getenv("_POD_ID")
}
if os.Getenv("_POD_SHORTNAME") != "" {
context["pod-shortname"] = os.Getenv("_POD_SHORTNAME")
}
if os.Getenv("_POD_REGION") != "" {
context["pod-region"] = os.Getenv("_POD_REGION")
}
if os.Getenv("_POD_ACCOUNT") != "" {
context["pod-account"] = os.Getenv("_POD_ACCOUNT")
}
logObj := Logger{
globals: context,
}
fl := defaultFormatLogger{}
logObj.fLogger = &fl
var logLvl LogLevel
strLogLvl := os.Getenv("KAYVEE_LOG_LEVEL")
if strLogLvl == "" {
logLvl = Trace
} else {
for key, val := range logLevelNames {
if strings.ToLower(strLogLvl) == val {
logLvl = key
break
}
}
}
logObj.SetConfig(source, logLvl, kv.Format, os.Stderr)
return &logObj
}
/////////////////////////////
//
// FormatLogger
//
/////////////////////////////
// formatLogger is an interface that abstracts the last steps in submitting a log
// message to a Logger: formatting and log writing. It can be replaced for testing.
// This is not yet exported, but could be if clients want customization of the
// format and writing steps.
type formatLogger interface {
// formatAndLog processes the given data map into a log line and writes it
formatAndLog(data map[string]interface{})
// setFormatter specifies the Formatter function to use in formatAndLog
setFormatter(formatter Formatter)
// setOutput specifies the output destination to use in formatAndLog
setOutput(output io.Writer)
}
// defaultFormatLogger provides default implementation of a formatLogger.
type defaultFormatLogger struct {
formatter Formatter
logWriter *log.Logger
}
// formatAndLog implements the formatLogger interface for *defaultFormatLogger.
func (fl *defaultFormatLogger) formatAndLog(data map[string]interface{}) {
logString := fl.formatter(data)
fl.logWriter.Println(logString)
}
// setFormat implements the formatLogger interface for *defaultFormatLogger.
func (fl *defaultFormatLogger) setFormatter(formatter Formatter) {
fl.formatter = formatter
}
// setOutput implements the formatLogger interface for *defaultFormatLogger.
func (fl *defaultFormatLogger) setOutput(output io.Writer) {
fl.logWriter = log.New(output, "", 0) // No prefixes
}