-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlogger.go
100 lines (83 loc) · 2.12 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
package binlog
import (
"fmt"
"io"
"log"
"os"
"sync"
"github.com/onlyac0611/binlog/dump"
)
//Logger 用于打印binlog包的调试日志
type Logger interface {
Errorf(string, ...interface{}) //错误日志打印
Infof(string, ...interface{}) //进程日志打印
Debugf(string, ...interface{}) //调试日志打印
Print(args ...interface{}) //打印dump包的错误日志
}
//LogLevel 日志级别, 为调试/信息/错误
type LogLevel uint8
//日志级别
const (
DebugLevel LogLevel = iota //调试
InfoLevel //信息
ErrorLevel //错误
)
type defaultLogger struct {
level LogLevel
logger *log.Logger
}
func newNilLogger() Logger {
d := &defaultLogger{
level: ErrorLevel,
logger: log.New(os.Stderr, "[binlog]", log.Lmicroseconds|log.LstdFlags|log.Lshortfile),
}
return d
}
//NewDefaultLogger 生成一个日志打印Logger,level可以是DebugLevel,InfoLevel,ErrorLevel
func NewDefaultLogger(writer io.Writer, level LogLevel) Logger {
d := &defaultLogger{
level: level,
logger: log.New(writer, "[binlog]", log.Lmicroseconds|log.LstdFlags|log.Lshortfile),
}
return d
}
func (d *defaultLogger) Errorf(format string, args ...interface{}) {
if d.level <= ErrorLevel {
d.logger.Output(2, fmt.Sprintf(format, args...))
}
}
func (d *defaultLogger) Infof(format string, args ...interface{}) {
if d.level <= InfoLevel {
d.logger.Output(2, fmt.Sprintf(format, args...))
}
}
func (d *defaultLogger) Debugf(format string, args ...interface{}) {
if d.level <= DebugLevel {
d.logger.Output(2, fmt.Sprintf(format, args...))
}
}
func (d *defaultLogger) Print(args ...interface{}) {
d.logger.Output(2, fmt.Sprint(args...))
}
var (
lw = loggerWrapper{l: newNilLogger()}
)
type loggerWrapper struct {
l Logger
mu sync.RWMutex
}
func (l *loggerWrapper) setLogger(logger Logger) {
l.mu.Lock()
defer l.mu.Unlock()
l.l = logger
}
func (l *loggerWrapper) logger() Logger {
l.mu.RLock()
defer l.mu.RUnlock()
return l.l
}
//SetLogger 设置一个符合Logger日志来打印binlog包的调试信息
func SetLogger(logger Logger) {
lw.setLogger(logger)
dump.SetLogger(logger)
}