forked from gookit/slog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
499 lines (406 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
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
package slog
import (
"context"
"os"
"sync"
"time"
"github.com/gookit/gsr"
)
// SLogger interface
type SLogger interface {
gsr.Logger
Log(level Level, v ...interface{})
Logf(level Level, format string, v ...interface{})
}
// Logger log dispatcher definition.
//
// The logger implements the `github.com/gookit/gsr.Logger`
type Logger struct {
name string
// lock for write logs
mu sync.Mutex
err error
handlers []Handler
processors []Processor
// reusable empty record
recordPool sync.Pool
//
// logger options
//
// LowerLevelName use lower level name
LowerLevelName bool
// ReportCaller on write log record
ReportCaller bool
CallerSkip int
CallerFlag uint8
// TimeClock custom time clock, timezone
TimeClock ClockFn
// handlers on exit.
exitHandlers []func()
// custom exit, panic handle.
ExitFunc func(code int)
PanicFunc func(v interface{})
}
// New create a new logger
func New() *Logger {
return NewWithName("logger")
}
// NewWithConfig create a new logger with config func
func NewWithConfig(fn func(l *Logger)) *Logger {
return NewWithName("logger").Configure(fn)
}
// NewWithHandlers create an new logger with handlers
func NewWithHandlers(hs ...Handler) *Logger {
logger := NewWithName("logger")
logger.AddHandlers(hs...)
return logger
}
// NewWithName create an new logger with name
func NewWithName(name string) *Logger {
logger := &Logger{
name: name,
// exit handle
ExitFunc: os.Exit,
PanicFunc: DefaultPanicFn,
exitHandlers: []func(){},
// options
ReportCaller: true,
CallerSkip: 5,
TimeClock: DefaultClockFn,
}
logger.recordPool.New = func() interface{} {
return newRecord(logger)
}
return logger
}
// NewRecord get new logger record
func (l *Logger) newRecord() *Record {
return l.recordPool.Get().(*Record)
}
func (l *Logger) releaseRecord(r *Record) {
// reset data
r.Time = emptyTime
r.Data = nil
r.Extra = nil
r.Fields = nil
r.CallerSkip = l.CallerSkip
l.recordPool.Put(r)
}
//
// ---------------------------------------------------------------------------
// Management logger
// ---------------------------------------------------------------------------
//
const flushInterval = 30 * time.Second
// Config current logger
func (l *Logger) Config(fns ...func(l *Logger)) *Logger {
for _, fn := range fns {
fn(l)
}
return l
}
// Configure current logger
func (l *Logger) Configure(fn func(l *Logger)) *Logger {
fn(l)
return l
}
// FlushDaemon run flush handle on daemon
//
// Usage:
// go slog.FlushDaemon()
func (l *Logger) FlushDaemon() {
for range time.NewTicker(flushInterval).C {
l.lockAndFlushAll()
}
}
// FlushTimeout flush logs on limit time.
// refer from glog package
func (l *Logger) FlushTimeout(timeout time.Duration) {
done := make(chan bool, 1)
go func() {
l.lockAndFlushAll()
// printlnStderr( "slog: flush logs error: ", err)
done <- true
}()
select {
case <-done:
case <-time.After(timeout):
printlnStderr("slog: flush took longer than timeout:", timeout)
}
}
// Sync flushes buffered logs (if any).
//
// alias of the Flush()
func (l *Logger) Sync() error { return Flush() }
// Flush flushes all the logs and attempts to "sync" their data to disk.
// l.mu is held.
func (l *Logger) Flush() error {
l.lockAndFlushAll()
return nil
}
// MustFlush flush logs. will ignore error
func (l *Logger) MustFlush() { l.lockAndFlushAll() }
// FlushAll flushes all the logs and attempts to "sync" their data to disk.
//
// alias of the Flush()
func (l *Logger) FlushAll() error {
l.lockAndFlushAll()
return nil
}
func (l *Logger) flushAll() {
// Flush from fatal down, in case there's trouble flushing.
l.VisitAll(func(handler Handler) error {
err := handler.Flush()
if err != nil {
l.err = err
printlnStderr("slog: call handler.Flush() failed. error:", err)
}
return nil
})
}
// lockAndFlushAll is like flushAll but locks l.mu first.
func (l *Logger) lockAndFlushAll() {
l.mu.Lock()
l.flushAll()
l.mu.Unlock()
}
// Close the logger
func (l *Logger) Close() error {
l.VisitAll(func(handler Handler) error {
// Flush logs and then close
err := handler.Close()
if err != nil {
l.err = err
printlnStderr("slog: call handler.Close() failed. error:", err)
}
return nil
})
return l.err
}
// VisitAll logger handlers
func (l *Logger) VisitAll(fn func(handler Handler) error) {
for _, handler := range l.handlers {
// you can return nil for ignore error
if err := fn(handler); err != nil {
return
}
}
}
// Reset the logger
func (l *Logger) Reset() {
l.ResetHandlers()
l.ResetProcessors()
}
// ResetProcessors for the logger
func (l *Logger) ResetProcessors() {
l.processors = make([]Processor, 0)
}
// ResetHandlers for the logger
func (l *Logger) ResetHandlers() {
l.handlers = make([]Handler, 0)
}
// Exit logger handle
func (l *Logger) Exit(code int) {
l.runExitHandlers()
// global exit handlers
runExitHandlers()
if l.ExitFunc == nil {
l.ExitFunc = os.Exit
}
l.ExitFunc(code)
}
// SetName for logger
func (l *Logger) SetName(name string) { l.name = name }
// Name of the logger
func (l *Logger) Name() string { return l.name }
// DoNothingOnPanicFatal do nothing on panic or fatal level.
// useful on testing.
func (l *Logger) DoNothingOnPanicFatal() {
l.PanicFunc = DoNothingOnPanic
l.ExitFunc = DoNothingOnExit
}
//
// ---------------------------------------------------------------------------
// Register handlers and processors
// ---------------------------------------------------------------------------
//
// AddHandler to the logger
func (l *Logger) AddHandler(h Handler) { l.handlers = append(l.handlers, h) }
// AddHandlers to the logger
func (l *Logger) AddHandlers(hs ...Handler) { l.handlers = append(l.handlers, hs...) }
// PushHandlers to the logger
func (l *Logger) PushHandlers(hs ...Handler) { l.handlers = append(l.handlers, hs...) }
// PushHandler to the l. alias of AddHandler()
func (l *Logger) PushHandler(h Handler) { l.AddHandler(h) }
// SetHandlers for the logger
func (l *Logger) SetHandlers(hs []Handler) { l.handlers = hs }
// AddProcessor to the logger
func (l *Logger) AddProcessor(p Processor) { l.processors = append(l.processors, p) }
// PushProcessor to the logger
// alias of AddProcessor()
func (l *Logger) PushProcessor(p Processor) { l.processors = append(l.processors, p) }
// AddProcessors to the logger
func (l *Logger) AddProcessors(ps ...Processor) { l.processors = append(l.processors, ps...) }
// SetProcessors for the logger
func (l *Logger) SetProcessors(ps []Processor) { l.processors = ps }
//
// ---------------------------------------------------------------------------
// New record with log data, fields
// ---------------------------------------------------------------------------
//
// Record return a new record for log
func (l *Logger) Record() *Record {
r := l.newRecord()
defer l.releaseRecord(r)
return r
}
// WithField new record with field
func (l *Logger) WithField(name string, value interface{}) *Record {
r := l.newRecord()
defer l.releaseRecord(r)
return r.WithField(name, value)
}
// WithFields new record with fields
func (l *Logger) WithFields(fields M) *Record {
r := l.newRecord()
defer l.releaseRecord(r)
return r.WithFields(fields)
}
// WithData new record with data
func (l *Logger) WithData(data M) *Record {
r := l.newRecord()
defer l.releaseRecord(r)
return r.WithData(data)
}
// WithTime new record with time.Time
func (l *Logger) WithTime(t time.Time) *Record {
r := l.newRecord()
defer l.releaseRecord(r)
return r.WithTime(t)
}
// WithContext new record with context.Context
func (l *Logger) WithContext(ctx context.Context) *Record {
r := l.newRecord()
defer l.releaseRecord(r)
return r.WithContext(ctx)
}
//
// ---------------------------------------------------------------------------
// Add log message with level
// ---------------------------------------------------------------------------
//
func (l *Logger) log(level Level, args []interface{}) {
r := l.newRecord()
r.CallerSkip++
r.log(level, args)
l.releaseRecord(r)
}
// Logf a format message with level
func (l *Logger) logf(level Level, format string, args []interface{}) {
r := l.newRecord()
r.CallerSkip++
r.logf(level, format, args)
l.releaseRecord(r)
}
// Log a message with level
func (l *Logger) Log(level Level, args ...interface{}) {
l.log(level, args)
}
// Logf a format message with level
func (l *Logger) Logf(level Level, format string, args ...interface{}) {
l.logf(level, format, args)
}
// Print logs a message at level PrintLevel
func (l *Logger) Print(args ...interface{}) {
l.log(PrintLevel, args)
}
// Println logs a message at level PrintLevel
func (l *Logger) Println(args ...interface{}) {
l.log(PrintLevel, args)
}
// Printf logs a message at level PrintLevel
func (l *Logger) Printf(format string, args ...interface{}) {
l.logf(PrintLevel, format, args)
}
// Warn logs a message at level Warn
func (l *Logger) Warn(args ...interface{}) {
l.log(WarnLevel, args)
}
// Warnf logs a message at level Warn
func (l *Logger) Warnf(format string, args ...interface{}) {
l.logf(WarnLevel, format, args)
}
// Warning logs a message at level Warn
func (l *Logger) Warning(args ...interface{}) {
l.log(WarnLevel, args)
}
// Info logs a message at level Info
func (l *Logger) Info(args ...interface{}) {
l.log(InfoLevel, args)
}
// Infof logs a message at level Info
func (l *Logger) Infof(format string, args ...interface{}) {
l.logf(InfoLevel, format, args)
}
// Trace logs a message at level Trace
func (l *Logger) Trace(args ...interface{}) {
l.log(TraceLevel, args)
}
// Tracef logs a message at level Trace
func (l *Logger) Tracef(format string, args ...interface{}) {
l.logf(TraceLevel, format, args)
}
// Error logs a message at level error
func (l *Logger) Error(args ...interface{}) {
l.log(ErrorLevel, args)
}
// Errorf logs a message at level Error
func (l *Logger) Errorf(format string, args ...interface{}) {
l.logf(ErrorLevel, format, args)
}
// ErrorT logs a error type at level Error
func (l *Logger) ErrorT(err error) {
if err != nil {
l.log(ErrorLevel, []interface{}{err})
}
}
// Notice logs a message at level Notice
func (l *Logger) Notice(args ...interface{}) {
l.log(NoticeLevel, args)
}
// Noticef logs a message at level Notice
func (l *Logger) Noticef(format string, args ...interface{}) {
l.logf(NoticeLevel, format, args)
}
// Debug logs a message at level Debug
func (l *Logger) Debug(args ...interface{}) {
l.log(DebugLevel, args)
}
// Debugf logs a message at level Debug
func (l *Logger) Debugf(format string, args ...interface{}) {
l.logf(DebugLevel, format, args)
}
// Fatal logs a message at level Fatal
func (l *Logger) Fatal(args ...interface{}) {
l.log(FatalLevel, args)
}
// Fatalf logs a message at level Fatal
func (l *Logger) Fatalf(format string, args ...interface{}) {
l.logf(FatalLevel, format, args)
}
// Fatalln logs a message at level Fatal
func (l *Logger) Fatalln(args ...interface{}) {
l.log(FatalLevel, args)
}
// Panic logs a message at level Panic
func (l *Logger) Panic(args ...interface{}) {
l.log(PanicLevel, args)
}
// Panicf logs a message at level Panic
func (l *Logger) Panicf(format string, args ...interface{}) {
l.logf(PanicLevel, format, args)
}
// Panicln logs a message at level Panic
func (l *Logger) Panicln(args ...interface{}) {
l.log(PanicLevel, args)
}