-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
584 lines (522 loc) · 17.5 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
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
package logo
import (
"bytes"
"fmt"
"log"
"os"
"runtime"
"strconv"
"strings"
"time"
)
type severity int
const (
debug severity = iota
info
warn
errorMsg
panicMsg
fatal
none
)
var severityName = []string{
"DEBUG",
"INFO",
"WARN",
"ERROR",
"PANIC",
"FATAL",
"",
}
func severityFromName(n string) severity {
n = strings.ToUpper(n)
for i, s := range severityName {
if s == n {
return severity(i)
}
}
// TODO: Should this return an error instead?
return none
}
type logManager struct {
appenders map[string]Appender
level severity
loggers map[string]*Logger
properties map[string]interface{}
}
var manager = newLogManager()
var defaultLogger = newDefaultLogger()
func newLogManager() *logManager {
m := logManager{
appenders: make(map[string]Appender),
loggers: make(map[string]*Logger),
properties: make(map[string]interface{}),
}
m.appenders["console"] = ConsoleAppender
return &m
}
func newDefaultLogger() *Logger {
l := New("", "debug")
l.callDepth = 3
return l
}
// SetGlobalProperty adds or updates a global level property in the log manager.
// During log output, global properties are combined with any contextual logger
// properties, and passed to the appenders. Standard appenders can include a
// property value by specifying it in the appender format string using the
// %property{name} syntax. For example:
//
// "%date %severity - %property{cluster-id} %message%newline"
//
// Note: global properties can be overridden by contextual loggers.
func SetGlobalProperty(name string, v interface{}) {
manager.properties[name] = v
}
// Close closes all appenders in the log manager.
// It is important that Close is called before exiting an application
// to ensure that any buffered data is written.
func Close() {
for _, a := range manager.appenders {
a.Close()
}
}
// AddAppender adds a named appender to the log manager.
// Returns an error if an appender of the same name has been
// added previously.
func AddAppender(name string, a Appender) error {
if _, ok := manager.appenders[name]; ok {
return fmt.Errorf("appender already exist")
}
manager.appenders[name] = a
return nil
}
// LogMessage is the structure passed to each appender of a logger.
type LogMessage struct {
bytes.Buffer
format string
args []interface{}
severity severity
name string
file string
line int
ctx string
timestamp time.Time
properties map[string]interface{}
}
// SetManagerLevel sets the minimum severity level for logging.
// This affects all managed loggers, regardless of their individual setting.
// For example, if the Warn() method is called on a logger with severity level "info",
// but the manager level is set to "error", no logging occurs.
// The default setting is "debug", which won't restrict any logging.
func SetManagerLevel(level string) {
sev := severityFromName(level)
manager.level = sev
}
var timenow = time.Now // to facilitate testing
var pool = make(chan *LogMessage, 50)
func getMessage() *LogMessage {
var m *LogMessage
select {
case m = <-pool:
m.Reset()
default:
m = &LogMessage{}
}
return m
}
func putMessage(m *LogMessage) {
// ditch large buffers
if m.Len() >= 250 {
return
}
select {
case pool <- m:
default: // pool full - continue
}
}
// New returns a new logger instance.
// Name can be any (non empty) string and is included in any log output
// (if specified in the appender format string). Normally this would be
// the name of a package using the logger. Level specifies the minimum
// severity for successful logging.
// For example, if the Warn() or Info() methods are called on a logger
// with severity level "info", then logging will be successful, but calls
// to Debug() will not.
// New panics if a logger with the same name has been created previously.
func New(name string, level string) *Logger {
if _, ok := manager.loggers[name]; ok {
panic(fmt.Sprintf("duplicate logger name, %q", name))
}
sev := severityFromName(level)
logger := &Logger{
level: sev,
name: name,
appenders: []Appender{ConsoleAppender},
callDepth: 2,
properties: make(map[string]interface{}),
}
manager.loggers[name] = logger
return logger
}
// LoggerByName returns a pointer to a logger named n.
// If no such named logger exists, LoggerByName creates
// a new logger instance with default level.
func LoggerByName(n string) *Logger {
l, ok := manager.loggers[n]
if !ok {
l = New(n, "")
}
return l
}
// Logger is a named logger owned by the log manager. The log manager has
// at least one default logger instance, but additional named loggers can
// be created with the New() method.
type Logger struct {
level severity
name string
appenders []Appender
context string
callDepth int
properties map[string]interface{}
} //m.properties = make(map[string]interface{}, len(manager.properties))
func fileline(depth int) (string, int) {
_, file, line, ok := runtime.Caller(depth)
if !ok {
file = "???"
line = 0
} else {
slash := strings.LastIndex(file, "/")
if slash >= 0 {
file = file[slash+1:]
}
}
return file, line
}
func (l *Logger) output(file string, line int, s severity, format string, args ...interface{}) {
if manager.level > debug && s < manager.level {
return
}
msg := getMessage()
msg.severity = s
msg.name = l.name
msg.ctx = l.context
msg.args = args
msg.format = format
msg.file = file
msg.line = line
msg.properties = make(map[string]interface{}, len(l.properties)+len(manager.properties))
for k, v := range manager.properties {
msg.properties[k] = v
}
for k, v := range l.properties {
msg.properties[k] = v
}
msg.timestamp = timenow()
for _, a := range l.appenders {
a.Append(msg)
}
putMessage(msg)
}
// SetAppenders specifies one or more appenders that the logger should use.
// Appenders are specified by their string name, and must have been added to
// the log manager previously using the AddAppender method.
// SetAppenders will panic if an appender name is not recognised.
func (l *Logger) SetAppenders(names ...string) error {
l.appenders = []Appender{}
var ok bool
for _, n := range names {
var a Appender
if a, ok = manager.appenders[n]; !ok {
return fmt.Errorf("unrecognised appender, [%s]", n)
}
l.appenders = append(l.appenders, a)
}
return nil
}
// WithContext returns a new context logger instance. The context logger
// is identical to its parent, with the exception that the context property
// is set and will appear in log messages (if specified in the appender
// format). Its primary purpose is for situations where you have a service
// which uses a named logger for general purpose logging, but also needs to
// log some messages with user related data (e.g. an HTTP correlationID
// header).
// The context parameter can be any type, but must implement the fmt.Stringer
// interface, as this will dictate its format in the log message.
//
// Deprecated: This method is deprecated. Use WithContextProperties instead.
func (l *Logger) WithContext(context fmt.Stringer) *Logger {
return &Logger{
level: l.level,
name: l.name,
appenders: l.appenders,
callDepth: l.callDepth,
context: context.String(),
}
}
// WithContextProperties returns a new child, context logger instance.
// The context logger is identical to its parent, with the exception that logger
// properties are updated with those specified in the context parameter. Logger
// properties are included in the log output to enable consumption by the
// appenders. Standard appenders can include a property by specifying it in the
// appender format string using the %property{} syntax. For example:
//
// "%date %severity - %property{username} %message%newline"
//
// Its primary purpose is for situations where you have a service which uses a
// named logger for general purpose logging, but also needs to log some messages
// with contextual/user-related data (e.g. an HTTP correlationID header, or a username).
// Global level properties can be set using SetGlobalProperty().
//
// Note: context properties override global properties with the same name.
func (l *Logger) WithContextProperties(context map[string]interface{}) *Logger {
return &Logger{
level: l.level,
name: l.name,
appenders: l.appenders,
callDepth: l.callDepth,
properties: context,
}
}
// SetContextProperty adds or updates the named context property with the value v.
func (l *Logger) SetContextProperty(name string, v interface{}) {
l.properties[name] = v
}
// Debug logs with a severity of "debug". Logging only succeeds if both
// the logger level (and manager level) are set to "debug".
// Arguments are handled in the same manner as fmt.Println.
func (l *Logger) Debug(args ...interface{}) {
if l.level > debug {
return
}
file, line := fileline(l.callDepth)
l.output(file, line, debug, "", args...)
}
// Debugf logs with a severity of "debug". Logging only succeeds if both
// the logger level (and manager level) are set to "debug".
// Arguments are handled in the same manner as fmt.Printf.
func (l *Logger) Debugf(format string, args ...interface{}) {
if l.level > debug {
return
}
file, line := fileline(l.callDepth)
l.output(file, line, debug, format, args...)
}
// Info logs with a severity of "info". Logging only succeeds if both the
// logger level (and manager level) are set to "info" or lower.
// Arguments are handled in the same manner as fmt.Println.
func (l *Logger) Info(args ...interface{}) {
if l.level > info {
return
}
file, line := fileline(l.callDepth)
l.output(file, line, info, "", args...)
}
// Infof logs with a severity of "info". Logging only succeeds if both the
// logger level (and manager level) are set to "info" or lower.
// Arguments are handled in the same manner as fmt.Printf.
func (l *Logger) Infof(format string, args ...interface{}) {
if l.level > info {
return
}
file, line := fileline(l.callDepth)
l.output(file, line, info, format, args...)
}
// Warn logs with a severity of "warn". Logging only succeeds if both the
// logger level (and manager level) are set to "warn" or lower.
// Arguments are handled in the same manner as fmt.Println.
func (l *Logger) Warn(args ...interface{}) {
if l.level > warn {
return
}
file, line := fileline(l.callDepth)
l.output(file, line, warn, "", args...)
}
// Warnf logs with a severity of "warn". Logging only succeeds if both the
// logger level (and manager level) are set to "warn" or lower.
// Arguments are handled in the same manner as fmt.Printf.
func (l *Logger) Warnf(format string, args ...interface{}) {
if l.level > warn {
return
}
file, line := fileline(l.callDepth)
l.output(file, line, warn, format, args...)
}
// Error logs with a severity of "error". Logging only succeeds if both the
// logger level (and manager level) are set to "error" or lower.
// Arguments are handled in the same manner as fmt.Println.
func (l *Logger) Error(args ...interface{}) {
if l.level > errorMsg {
return
}
file, line := fileline(l.callDepth)
l.output(file, line, errorMsg, "", args...)
}
// Errorf logs with a severity of "error". Logging only succeeds if both the
// logger level (and manager level) are set to "error" or lower.
// Arguments are handled in the same manner as fmt.Printf.
func (l *Logger) Errorf(format string, args ...interface{}) {
if l.level > errorMsg {
return
}
file, line := fileline(l.callDepth)
l.output(file, line, errorMsg, format, args...)
}
// Panic logs with a severity of "panic", and then panics with the
// supplied parameters. Logging only succeeds if both the
// logger level (and manager level) are set to "panic" or lower.
// Arguments are handled in the same manner as fmt.Println.
func (l *Logger) Panic(args ...interface{}) {
if l.level <= panicMsg {
file, line := fileline(l.callDepth)
l.output(file, line, panicMsg, "", args...)
}
panic(fmt.Sprint(args...))
}
// Panicf logs with a severity of "panic", and then panics with the
// supplied parameters. Logging only succeeds if both the
// logger level (and manager level) are set to "panic" or lower.
// Arguments are handled in the same manner as fmt.Printf.
func (l *Logger) Panicf(format string, args ...interface{}) {
if l.level <= panicMsg {
file, line := fileline(l.callDepth)
l.output(file, line, panicMsg, format, args...)
}
panic(fmt.Sprintf(format, args...))
}
var exit = func(i int) { os.Exit(i) } // to facilitate testing
// Fatal logs with a severity of "fatal", and then calls Exit.
// Logging only succeeds if both the logger level (and manager level)
// are set to "fatal" or lower.
// Arguments are handled in the same manner as fmt.Println.
func (l *Logger) Fatal(args ...interface{}) {
file, line := fileline(l.callDepth)
l.output(file, line, fatal, "", args...)
Close()
exit(1)
}
// Fatalf logs with a severity of "fatal", and then calls Exit.
// Logging only succeeds if both the logger level (and manager level)
// are set to "fatal" or lower.
// Arguments are handled in the same manner as fmt.Printf.
func (l *Logger) Fatalf(format string, args ...interface{}) {
file, line := fileline(l.callDepth)
l.output(file, line, fatal, format, args...)
Close()
exit(1)
}
// SetAppenders specifies one or more appenders for the default logger.
// Appenders are specified by their string name, and must have been added to
// the log manager previously using the AddAppender method.
// SetAppenders will panic if an appender name is not recognised.
func SetAppenders(names ...string) {
defaultLogger.SetAppenders(names...)
}
// Debugf logs to the default logger with a severity of "debug".
// Logging only succeeds if the manager level is set to "debug".
// Arguments are handled in the same manner as fmt.Printf.
func Debugf(format string, args ...interface{}) {
defaultLogger.Debugf(format, args...)
}
// Debug logs to the default logger with a severity of "debug".
// Logging only succeeds if the manager level is set to "debug".
// Arguments are handled in the same manner as fmt.Println.
func Debug(args ...interface{}) {
defaultLogger.Debug(args...)
}
// Infof logs to the default logger with a severity of "info".
// Logging only succeeds if the manager level is set to "info" or lower.
// Arguments are handled in the same manner as fmt.Printf.
func Infof(format string, args ...interface{}) {
defaultLogger.Infof(format, args...)
}
// Info logs to the default logger with a severity of "info".
// Logging only succeeds if the manager level is set to "info" or lower.
// Arguments are handled in the same manner as fmt.Println.
func Info(args ...interface{}) {
defaultLogger.Info(args...)
}
// Warnf logs to the default logger with a severity of "warn".
// Logging only succeeds if the manager level is set to "warn" or lower.
// Arguments are handled in the same manner as fmt.Printf.
func Warnf(format string, args ...interface{}) {
defaultLogger.Warnf(format, args...)
}
// Warn logs to the default logger with a severity of "warn".
// Logging only succeeds if the manager level is set to "warn" or lower.
// Arguments are handled in the same manner as fmt.Println.
func Warn(args ...interface{}) {
defaultLogger.Warn(args...)
}
// Errorf logs to the default logger with a severity of "error".
// Logging only succeeds if the manager level is set to "error" or lower.
// Arguments are handled in the same manner as fmt.Printf.
func Errorf(format string, args ...interface{}) {
defaultLogger.Errorf(format, args...)
}
// Error logs to the default logger with a severity of "error".
// Logging only succeeds if the manager level is set to "error" or lower.
// Arguments are handled in the same manner as fmt.Println.
func Error(args ...interface{}) {
defaultLogger.Error(args...)
}
// Panicf logs to the default logger with a severity of "panic", and then
// panics with the supplied parameters. Logging only succeeds if the manager
// level is set to "panic" or lower.
// Arguments are handled in the same manner as fmt.Printf.
func Panicf(format string, args ...interface{}) {
defaultLogger.Panicf(format, args...)
}
// Panic logs to the default logger with a severity of "panic", and then
// panics with the supplied parameters. Logging only succeeds if the manager
// level is set to "panic" or lower.
// Arguments are handled in the same manner as fmt.Println.
func Panic(args ...interface{}) {
defaultLogger.Panic(args...)
}
// Fatalf logs to the default logger with a severity of "fatal", and then
// calls Exit. Logging only succeeds if the manager level is set to "fatal"
// or lower.
// Arguments are handled in the same manner as fmt.Printf.
func Fatalf(format string, args ...interface{}) {
defaultLogger.Fatalf(format, args...)
}
// Fatal logs to the default logger with a severity of "fatal", and then
// calls Exit. Logging only succeeds if the manager level is set to "fatal"
// or lower.
// Arguments are handled in the same manner as fmt.Println.
func Fatal(args ...interface{}) {
defaultLogger.Fatal(args...)
}
// CaptureStandardLog hooks into the standard go log package and redirects
// the output to appenders.
func CaptureStandardLog(appenders ...string) {
b := bridge{
Logger: Logger{level: none},
}
b.SetAppenders(appenders...)
log.SetFlags(log.Lshortfile)
log.SetOutput(b)
}
type bridge struct {
Logger
}
func (l bridge) Write(b []byte) (n int, err error) {
var msg string
file := "???"
line := 0
// format is "file.go:1234: message"
parts := bytes.SplitN(b, []byte{':'}, 3)
if len(parts) != 3 || len(parts[0]) == 0 || len(parts[2]) == 0 {
msg = fmt.Sprintf("(Invalid log format): %s", b)
} else {
file = string(parts[0])
msg = string(parts[2])
line, err = strconv.Atoi(string(parts[1]))
if err != nil {
msg = fmt.Sprintf("(Invalid line number): %s", b)
}
}
msg = strings.TrimSpace(msg)
l.output(file, line, l.level, msg)
return len(b), nil
}