-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlogger.go
121 lines (101 loc) · 2.25 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
package coze
import (
"context"
"fmt"
"log"
"os"
)
// Logger ...
type Logger interface {
Log(ctx context.Context, level LogLevel, message string, args ...interface{})
}
type LevelLogger interface {
Logger
SetLevel(level LogLevel)
}
type LogLevel int
// LogLevelTrace ...
const (
LogLevelTrace LogLevel = iota + 1
LogLevelDebug
LogLevelInfo
LogLevelWarn
LogLevelError
)
// String ...
func (r LogLevel) String() string {
switch r {
case LogLevelTrace:
return "TRACE"
case LogLevelDebug:
return "DEBUG"
case LogLevelInfo:
return "INFO"
case LogLevelWarn:
return "WARN"
case LogLevelError:
return "ERROR"
default:
return ""
}
}
type stdLogger struct {
log *log.Logger
}
// newStdLogger ...
func newStdLogger() Logger {
return &stdLogger{
log: log.New(os.Stderr, "", log.LstdFlags),
}
}
// Log ...
func (l *stdLogger) Log(ctx context.Context, level LogLevel, message string, args ...interface{}) {
if len(args) == 0 {
_ = l.log.Output(2, "["+level.String()+"] "+message)
} else {
_ = l.log.Output(2, "["+level.String()+"] "+fmt.Sprintf(message, args...))
}
}
type levelLogger struct {
Logger
level LogLevel
}
// NewLevelLogger ...
func NewLevelLogger(logger Logger, level LogLevel) LevelLogger {
return &levelLogger{
Logger: logger,
level: level,
}
}
// SetLevel ...
func (l *levelLogger) SetLevel(level LogLevel) {
l.level = level
}
// Log ...
func (l *levelLogger) Log(ctx context.Context, level LogLevel, message string, args ...interface{}) {
if level >= l.level {
l.Logger.Log(ctx, level, message, args...)
}
}
func (l *levelLogger) Debugf(ctx context.Context, message string, args ...interface{}) {
l.Log(ctx, LogLevelDebug, message, args...)
}
func (l *levelLogger) Infof(ctx context.Context, message string, args ...interface{}) {
l.Log(ctx, LogLevelInfo, message, args...)
}
func (l *levelLogger) Warnf(ctx context.Context, message string, args ...interface{}) {
l.Log(ctx, LogLevelWarn, message, args...)
}
func (l *levelLogger) Errorf(ctx context.Context, message string, args ...interface{}) {
l.Log(ctx, LogLevelError, message, args...)
}
var logger = levelLogger{
Logger: newStdLogger(),
level: LogLevelInfo,
}
func setLogger(l Logger) {
logger.Logger = l
}
func setLevel(level LogLevel) {
logger.level = level
}