/
log4go.go
103 lines (90 loc) · 2.64 KB
/
log4go.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
package log4go
import (
"context"
"sync"
)
var defaultLogger Logger
var loggers map[string]Logger
var loggerOnce sync.Once
var loggerMutex sync.Mutex
// SetLogger set logger
func SetLogger(name string, log Logger) {
loggerOnce.Do(func() {
loggers = make(map[string]Logger)
})
loggerMutex.Lock()
defer loggerMutex.Unlock()
loggers[name] = log
}
// GetLogger get Logger
func GetLogger(name string) Logger {
return loggers[name]
}
// SetDefaultLogger 设置默认Logger
func SetDefaultLogger(dlog Logger) {
defaultLogger = dlog
}
// Info logs a message at InfoLevel. The message includes any fields passed
// at the log site, as well as any fields accumulated on the logger.
func Info(ctx context.Context, msg string, fields ...Field) {
if defaultLogger == nil {
return
}
defaultLogger.Info(ctx, msg, fields...)
}
// Debug logs a message at DebugLevel. The message includes any fields passed
// at the log site, as well as any fields accumulated on the logger.
func Debug(ctx context.Context, msg string, fields ...Field) {
if defaultLogger == nil {
return
}
defaultLogger.Debug(ctx, msg, fields...)
}
// Warn logs a message at WarnLevel. The message includes any fields passed
// at the log site, as well as any fields accumulated on the logger.
func Warn(ctx context.Context, msg string, fields ...Field) {
if defaultLogger == nil {
return
}
defaultLogger.Warn(ctx, msg, fields...)
}
// Error logs a message at ErrorLevel. The message includes any fields passed
// at the log site, as well as any fields accumulated on the logger.
func Error(ctx context.Context, msg string, fields ...Field) {
if defaultLogger == nil {
return
}
defaultLogger.Error(ctx, msg, fields...)
}
// Panic logs a message at PanicLevel. The message includes any fields passed
// at the log site, as well as any fields accumulated on the logger.
//
// The logger then panics, even if logging at PanicLevel is disabled.
func Panic(ctx context.Context, msg string, fields ...Field) {
if defaultLogger == nil {
return
}
defaultLogger.Panic(ctx, msg, fields...)
}
// Fatal logs a message at FatalLevel. The message includes any fields passed
// at the log site, as well as any fields accumulated on the logger.
//
// The logger then calls os.Exit(1), even if logging at FatalLevel is
// disabled.
func Fatal(ctx context.Context, msg string, fields ...Field) {
if defaultLogger == nil {
return
}
defaultLogger.Fatal(ctx, msg, fields...)
}
// Sync flushing any buffered log entries.
//
// Applications should take care to call Sync before exiting.
func Sync(ctx context.Context) {
if defaultLogger != nil {
defaultLogger.Sync(ctx)
}
for _, v := range loggers {
v.Sync(ctx)
}
}