-
Notifications
You must be signed in to change notification settings - Fork 1
/
logging.go
690 lines (594 loc) · 15.9 KB
/
logging.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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
// Copyright (C) 2019-2020, Xiongfa Li.
// @author xiongfa.li
// @version V1.0
// Description:
package xlog
import (
"bytes"
"fmt"
"github.com/xfali/xlog/value"
"io"
"os"
"runtime"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
)
type Level = int32
const (
FATAL Level = 0
PANIC Level = 1
ERROR Level = 2
WARN Level = 3
INFO Level = 4
DEBUG Level = 5
)
const (
//不显示调用信息
CallerNone = 0
//只显示文件名
CallerShortFile = 1
//显示文件名及路径
CallerLongFile = 1 << 1
//file mask
CallerFileMask = 3
//只显示函数名
CallerShortFunc = 1 << 2
//显示完整函数名
CallerLongFunc = 1 << 3
//显示简单函数名
CallerSimpleFunc = 1 << 4
//func mask
CallerFuncMask = 7 << 2
)
const (
//自动填充颜色
AutoColor = iota
//禁用颜色
DisableColor
//强制使用颜色
ForceColor
)
const (
// 时间戳的Key
KeyTimestamp = "LogTime"
// 日志级别key
KeySeverityLevel = "LogLevel"
// 调用者Key
KeyCaller = "LogCaller"
// 日志内容Key
KeyContent = "LogContent"
// 日志名称Key
KeyName = "LogName"
)
var (
//前景色
ColorGreen = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
ColorWhite = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
ColorYellow = string([]byte{27, 91, 57, 48, 59, 52, 51, 109})
ColorRed = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
ColorBlue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})
ColorMagenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})
ColorCyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})
ColorReset = string([]byte{27, 91, 48, 109})
ForeGreen = "\033[97;32m"
ForeWhite = "\033[90;37m"
ForeYellow = "\033[90;33m"
ForeRed = "\033[97;31m"
ForeBlue = "\033[97;34m"
ForeMagenta = "\033[97;35m"
ForeCyan = "\033[97;36m"
//背景色
BackGreen = "\033[97;42m"
BackWhite = "\033[90;47m"
BackYellow = "\033[90;43m"
BackRed = "\033[97;41m"
BackBlue = "\033[97;44m"
BackMagenta = "\033[97;45m"
BackCyan = "\033[97;46m"
ResetColor = "\033[0m"
)
// 级别及名称映射
var LogTag = map[Level]string{
DEBUG: "DEBUG",
INFO: "INFO",
WARN: "WARN",
ERROR: "ERROR",
PANIC: "PANIC",
FATAL: "FATAL",
}
// 默认值
var (
DefaultColorFlag = DisableColor
DefaultPrintFileFlag = CallerShortFile
DefaultFatalNoTrace = false
DefaultLevel = INFO
DefaultWriters = map[Level]io.Writer{
DEBUG: os.Stdout,
INFO: os.Stdout,
WARN: os.Stdout,
ERROR: os.Stderr,
PANIC: os.Stderr,
FATAL: os.Stderr,
}
)
type LoggingOpt func(l *logging)
// Logging是xlog的日志基础工具,向下对接日志输出Writer,向上提供日志操作接口
type Logging interface {
// 输出format日志(线程安全)
// Param: level日志级别, depth调用深度, keyValues附加的日志内容(多用于添加固定的日志信息), format格式化的格式, args参数
Logf(level Level, depth int, keyValues KeyValues, format string, args ...interface{})
// 解析并输出参数(线程安全)
// Param: level日志级别, depth调用深度, keyValues附加的日志内容(多用于添加固定的日志信息), args参数
Log(level Level, depth int, keyValues KeyValues, args ...interface{})
// 解析并输出参数,末尾增加换行(线程安全)
// Param: level日志级别, depth调用深度, keyValues附加的日志内容(多用于添加固定的日志信息), args参数
Logln(level Level, depth int, keyValues KeyValues, args ...interface{})
// 设置日志格式化工具(线程安全)
SetFormatter(f Formatter)
// 设置日志严重级别,低于该级别的将不被输出(线程安全)
SetSeverityLevel(severityLevel Level)
// 判断参数级别是否会输出(线程安全)
IsEnabled(severityLevel Level) bool
// 设置输出的Writer,注意该方法会将所有级别都配置为参数writer(线程安全)
SetOutput(w io.Writer)
// 设置对应日志级别的Writer(线程安全)
SetOutputBySeverity(severityLevel Level, w io.Writer)
// 获得对应日志级别的Writer(线程安全)
GetOutputBySeverity(severityLevel Level) io.Writer
// 获得一个clone的对象(线程安全)
Clone() Logging
}
type ExitFunc func(code int)
type PanicFunc func(interface{})
type logging struct {
timeFormatter func(t time.Time) string
callerFormatter func(file string, line int, funcName string) string
exitFunc ExitFunc
panicFunc PanicFunc
formatter atomic.Value
colorFlag int
fileFlag int
fatalNoTrace bool
level Level
writers sync.Map
bufPool sync.Pool
}
var defaultLogging value.Value = value.NewSimpleValue(Logging(NewLogging()))
func NewLogging(opts ...LoggingOpt) Logging {
ret := &logging{
timeFormatter: TimeFormat,
callerFormatter: CallerFormat,
exitFunc: defaultExit,
panicFunc: defaultPanic,
//formatter: nil,
colorFlag: DefaultColorFlag,
fileFlag: DefaultPrintFileFlag,
fatalNoTrace: DefaultFatalNoTrace,
level: DefaultLevel,
//writers: map[Level]io.Writer{},
bufPool: sync.Pool{New: func() interface{} {
return bytes.NewBuffer(nil)
}},
}
for k, v := range DefaultWriters {
ret.writers.Store(k, v)
}
for _, v := range opts {
v(ret)
}
return ret
}
func (l *logging) getCaller(depth int) string {
if l.fileFlag != CallerNone {
pc, file, line, ok := runtime.Caller(3 + depth)
if !ok {
return "???"
}
if (l.fileFlag & CallerShortFile) != 0 {
file = shortFile(file)
}
if (l.fileFlag & CallerFileMask) == 0 {
file = ""
line = -1
}
var funcName string
if (l.fileFlag & CallerFuncMask) != 0 {
funcName = runtime.FuncForPC(pc).Name()
if (l.fileFlag & CallerShortFunc) != 0 {
idx := strings.LastIndex(funcName, ".")
if idx != -1 && idx < (len(funcName)-1) {
funcName = funcName[idx+1:]
}
} else if (l.fileFlag & CallerSimpleFunc) != 0 {
funcName = simpleFuncName(funcName)
}
}
return l.callerFormatter(file, line, funcName)
}
return ""
}
func (l *logging) format(writer io.Writer, level Level, depth int, keyValues KeyValues, log string) {
caller := l.getCaller(depth)
var (
lvColor string
resetColor string
)
if l.colorFlag == AutoColor {
lvColor = selectLevelColor(level)
resetColor = ResetColor
}
//if log == "" || log[len(log)-1] != '\n' {
// log += "\n"
//}
formatter := l.formatter.Load()
if formatter != nil {
innerKvs := NewKeyValues()
innerKvs.Add(KeyTimestamp, time.Now(), KeySeverityLevel, LogTag[level], KeyCaller, caller)
MergeKeyValues(innerKvs, keyValues)
if log == "\n" {
log = ""
}
innerKvs.Add(KeyContent, log)
formatter.(Formatter).Format(writer, innerKvs)
} else {
writer.Write([]byte(fmt.Sprintf("%s [%s%s%s] %s %s%s",
l.timeFormatter(time.Now()), lvColor, LogTag[level], resetColor, caller, l.formatKeyValues(keyValues), log)))
}
}
func (l *logging) formatKeyValues(keyValues KeyValues) string {
if keyValues == nil || keyValues.Len() == 0 {
return ""
}
buf := bytes.Buffer{}
for _, k := range keyValues.Keys() {
buf.WriteString(l.formatValue(keyValues.Get(k)))
buf.WriteByte(' ')
}
return buf.String()
}
func (l *logging) formatValue(o interface{}) string {
if o == nil {
return ""
}
if t, ok := o.(time.Time); ok {
if l.timeFormatter != nil {
return l.timeFormatter(t)
}
}
return formatValue(o, false)
}
func selectLevelColor(level Level) string {
if level == INFO {
return ForeCyan
} else if level == WARN {
return ForeYellow
} else if level < WARN {
return ForeRed
}
return ""
}
func (l *logging) Logf(level Level, depth int, keyValues KeyValues, format string, args ...interface{}) {
if !l.IsEnabled(level) {
return
}
length := len(format)
if length > 0 {
if format[length-1] != '\n' {
format = format + "\n"
}
}
logInfo := fmt.Sprintf(format, args...)
w := l.selectWriter(level)
l.format(w, level, depth, keyValues, logInfo)
if level == PANIC {
l.panicFunc(NewKeyValues(KeyContent, logInfo))
} else if level <= FATAL {
l.processFatal(w)
}
//l.output(level, buf)
}
func (l *logging) Log(level Level, depth int, keyValues KeyValues, args ...interface{}) {
if !l.IsEnabled(level) {
return
}
logInfo := fmt.Sprint(args...)
w := l.selectWriter(level)
l.format(w, level, depth, keyValues, logInfo)
if level == PANIC {
l.panicFunc(NewKeyValues(KeyContent, logInfo))
} else if level <= FATAL {
l.processFatal(w)
}
}
func (l *logging) Logln(level Level, depth int, keyValues KeyValues, args ...interface{}) {
if !l.IsEnabled(level) {
return
}
logInfo := fmt.Sprintln(args...)
w := l.selectWriter(level)
l.format(w, level, depth, keyValues, logInfo)
if level == PANIC {
l.panicFunc(NewKeyValues(KeyContent, logInfo))
} else if level <= FATAL {
l.processFatal(w)
}
}
func (l *logging) getBuffer() *bytes.Buffer {
buf := l.bufPool.Get().(*bytes.Buffer)
buf.Reset()
return buf
}
func (l *logging) putBuffer(buf *bytes.Buffer) {
if buf == nil {
return
}
if buf.Len() > 256 {
//let big buffers die a natural death.
return
}
l.bufPool.Put(buf)
}
func (l *logging) processFatal(writer io.Writer) {
if !l.fatalNoTrace {
trace := stacks(true)
writer.Write(trace)
}
l.exitFunc(-1)
}
func (l *logging) Clone() Logging {
ret := &logging{
timeFormatter: l.timeFormatter,
callerFormatter: l.callerFormatter,
//formatter: l.formatter,
colorFlag: l.colorFlag,
fileFlag: l.fileFlag,
fatalNoTrace: l.fatalNoTrace,
level: l.level,
//writers: map[Level]io.Writer{},
bufPool: sync.Pool{New: func() interface{} {
return bytes.NewBuffer(nil)
}},
}
ret.formatter.Store(l.formatter.Load())
l.writers.Range(func(key, value interface{}) bool {
ret.writers.Store(key, value)
return true
})
return ret
}
//func (l *logging) output(level int) {
// if level >= FATAL {
// if !l.fatalNoTrace {
// trace := stacks(true)
// buf.WriteString("\n")
// buf.Write(trace)
// }
// l.selectWriter(level).Write(buf.Bytes())
// os.Exit(-1)
// } else {
// l.selectWriter(level).Write(buf.Bytes())
// }
// l.putBuffer(buf)
//}
func (l *logging) selectWriter(level Level) io.Writer {
for i := level; i <= DEBUG; i++ {
v, ok := l.writers.Load(i)
if ok && v != nil {
return v.(io.Writer)
}
}
return os.Stdout
}
func (l *logging) SetFormatter(f Formatter) {
l.formatter.Store(f)
}
func (l *logging) GetFormatter() Formatter {
v := l.formatter.Load()
if v == nil {
return nil
}
return v.(Formatter)
}
func (l *logging) SetSeverityLevel(severity Level) {
atomic.StoreInt32(&l.level, severity)
}
func (l *logging) IsEnabled(severityLevel Level) bool {
return atomic.LoadInt32(&l.level) >= severityLevel
}
// Logging不会自动为输出的Writer加锁,如果需要加锁请使用LockedWriter:
// logging.SetOutPut(&writer.LockedWriter{w})
func (l *logging) SetOutput(w io.Writer) {
for i := FATAL; i <= DEBUG; i++ {
l.writers.Store(i, w)
}
}
// Logging不会自动为输出的Writer加锁,如果需要加锁请使用LockedWriter:
// logging.SetOutputBySeverity(level, &writer.LockedWriter{w})
func (l *logging) SetOutputBySeverity(severityLevel Level, w io.Writer) {
l.writers.Store(severityLevel, w)
}
func (l *logging) GetOutputBySeverity(severityLevel Level) io.Writer {
v, ok := l.writers.Load(severityLevel)
if !ok {
return nil
}
return v.(io.Writer)
}
func shortFile(file string) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
return short
}
func stacks(all bool) []byte {
n := 10000
if all {
n = 100000
}
var trace []byte
for i := 0; i < 5; i++ {
trace = make([]byte, n)
nbytes := runtime.Stack(trace, all)
if nbytes < len(trace) {
return trace[:nbytes]
}
}
return trace
}
func TimeFormat(t time.Time) string {
var timeString = t.Format("2006-01-02 15:04:05")
return timeString
}
func CallerFormat(file string, line int, funcName string) string {
//no file
if file != "" {
if funcName == "" {
return fmt.Sprintf("%s:%d", file, line)
} else {
return fmt.Sprintf("%s:%d (%s)", file, line, funcName)
}
} else {
if funcName == "" {
return ""
} else {
return "(" + funcName + ")"
}
}
}
// 配置内置Logging实现的时间格式化函数
func SetTimeFormatter(f func(t time.Time) string) func(*logging) {
return func(logging *logging) {
logging.timeFormatter = f
}
}
// 配置内置Logging实现的时间格式化函数
func SetCallerFormatter(f func(file string, line int, funcName string) string) func(*logging) {
return func(logging *logging) {
logging.callerFormatter = f
}
}
// 配置内置Logging Fatal退出处理函数
func SetExitFunc(f ExitFunc) func(*logging) {
return func(logging *logging) {
logging.exitFunc = f
}
}
// 配置内置Logging Panic处理函数
func SetPanicFunc(f PanicFunc) func(*logging) {
return func(logging *logging) {
logging.panicFunc = f
}
}
func defaultExit(code int) {
pid := os.Getpid()
p, err := os.FindProcess(pid)
if err != nil {
os.Exit(code)
} else {
if err = p.Signal(os.Interrupt); err != nil {
// Per https://golang.org/pkg/os/#Signal, “Interrupt is not implemented on
// Windows; using it with os.Process.Signal will return an error.”
// Fall back to Kill instead.
if err = p.Signal(syscall.SIGTERM); err != nil {
if err = p.Kill(); err != nil {
os.Exit(code)
}
}
}
}
}
func defaultPanic(v interface{}) {
panic(v)
}
func simpleFuncName(funcName string) string {
segs := strings.Split(funcName, "/")
buf := strings.Builder{}
buf.Grow(len(funcName) / 2)
size := len(segs) - 1
for i := 0; i < size; i++ {
if len(segs[i]) > 0 {
buf.WriteString(segs[i][:1])
buf.WriteString(".")
}
}
buf.WriteString(segs[size])
return buf.String()
}
// 配置内置Logging实现的颜色的标志,有AutoColor、DisableColor、ForceColor
func SetColorFlag(flag int) func(*logging) {
return func(logging *logging) {
logging.colorFlag = flag
}
}
// 配置内置Logging实现的文件输出标志,有ShortFile、LongFile
func SetCallerFlag(flag int) func(*logging) {
return func(logging *logging) {
logging.fileFlag = flag
}
}
// 配置内置Logging实现是否在发生致命错误时打印堆栈,默认打印
func SetFatalNoTrace(noTrace bool) func(*logging) {
return func(logging *logging) {
logging.fatalNoTrace = noTrace
}
}
// 设置默认Logging的日志格式化工具
func SetFormatter(f Formatter) {
defaultLogging.Load().(Logging).SetFormatter(f)
}
// 设置默认Logging的日志严重级别
func SetSeverityLevel(severity Level) {
defaultLogging.Load().(Logging).SetSeverityLevel(severity)
}
// 检查是否输出参数级别的日志
func IsEnabled(severityLevel Level) bool {
return defaultLogging.Load().(Logging).IsEnabled(severityLevel)
}
// 设置默认Logging的输出
func SetOutput(w io.Writer) {
defaultLogging.Load().(Logging).SetOutput(w)
}
// 设置默认Logging对应日志级别的输出
func SetOutputBySeverity(severity Level, w io.Writer) {
defaultLogging.Load().(Logging).SetOutputBySeverity(severity, w)
}
// 获得默认Logging对应日志级别的输出
func GetOutputBySeverity(severity Level) io.Writer {
return defaultLogging.Load().(Logging).GetOutputBySeverity(severity)
}
// 获得默认Logging
func DefaultLogging() Logging {
return defaultLogging.Load().(Logging)
}
// 配置默认的Logging、Factory value(非线程安全)
// 可以配置为线程安全(value.AtomicValue)的和非线程安全的(value.SimpleValue)
func InitUnsafe(logging, factory value.Value) {
defaultLogging = logging
defaultFactory = factory
}
var once = sync.Once{}
// 配置默认的Logging、Factory value(线程安全且只能初始化一次)
// 可以配置为线程安全(value.AtomicValue)的和非线程安全的(value.SimpleValue)
func InitOnce(logging, factory value.Value) {
once.Do(func() {
defaultLogging = logging
defaultFactory = factory
})
}
const autogeneratedFrameName = "<autogenerated>"
func FramesToCaller() int {
for i := 1; i < 3; i++ {
_, file, _, _ := runtime.Caller(i + 1)
if file != autogeneratedFrameName {
return i
}
}
return 1
}