-
Notifications
You must be signed in to change notification settings - Fork 5
/
logger.go
248 lines (216 loc) · 6.16 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
package log
import (
"bytes"
"fmt"
"io"
"sync"
"sync/atomic"
"time"
"unsafe"
)
type Logger interface {
// Fatal logs a message at FatalLevel.
//
// Unlike other golang log libraries (for example, the golang standard log library),
// Fatal just logs a message and does not call os.Exit, so you need to explicitly call os.Exit if necessary.
//
// For fields, the following conditions must be satisfied
// 1. the len(fields) must be an even number, that is to say len(fields)%2==0
// 2. the even index element of fields must be non-empty string
Fatal(msg string, fields ...interface{})
// Error logs a message at ErrorLevel.
// The requirements for fields can see the comments of Fatal.
Error(msg string, fields ...interface{})
// Warn logs a message at WarnLevel.
// The requirements for fields can see the comments of Fatal.
Warn(msg string, fields ...interface{})
// Info logs a message at InfoLevel.
// The requirements for fields can see the comments of Fatal.
Info(msg string, fields ...interface{})
// Debug logs a message at DebugLevel.
// The requirements for fields can see the comments of Fatal.
Debug(msg string, fields ...interface{})
// Output logs a message at specified level.
//
// For level==FatalLevel, unlike other golang log libraries (for example, the golang standard log library),
// Output just logs a message and does not call os.Exit, so you need to explicitly call os.Exit if necessary.
//
// The requirements for fields can see the comments of Fatal.
Output(calldepth int, level Level, msg string, fields ...interface{})
// WithField creates a new Logger from the current Logger and adds a field to it.
WithField(key string, value interface{}) Logger
// WithFields creates a new Logger from the current Logger and adds multiple fields to it.
// The requirements for fields can see the comments of Fatal.
WithFields(fields ...interface{}) Logger
// SetFormatter sets the logger formatter.
SetFormatter(Formatter)
// SetOutput sets the logger output.
SetOutput(io.Writer)
// SetLevel sets the logger level.
SetLevel(Level) error
// SetLevelString sets the logger level.
SetLevelString(string) error
}
type Formatter interface {
Format(*Entry) ([]byte, error)
}
type Entry struct {
Location string // function(file:line)
Time time.Time
Level Level
TraceId string
Message string
Fields map[string]interface{}
Buffer *bytes.Buffer
}
func New(opts ...Option) Logger { return _New(opts) }
func _New(opts []Option) *logger {
l := &logger{}
l.setOptions(newOptions(opts))
return l
}
type logger struct {
mu sync.Mutex // protects the following options field
options unsafe.Pointer // *options
fields map[string]interface{}
}
func (l *logger) getOptions() (opts *options) {
return (*options)(atomic.LoadPointer(&l.options))
}
func (l *logger) setOptions(opts *options) {
atomic.StorePointer(&l.options, unsafe.Pointer(opts))
}
func (l *logger) SetFormatter(formatter Formatter) {
if formatter == nil {
return
}
l.mu.Lock()
defer l.mu.Unlock()
opts := *l.getOptions()
opts.SetFormatter(formatter)
l.setOptions(&opts)
}
func (l *logger) SetOutput(output io.Writer) {
if output == nil {
return
}
l.mu.Lock()
defer l.mu.Unlock()
opts := *l.getOptions()
opts.SetOutput(output)
l.setOptions(&opts)
}
func (l *logger) SetLevel(level Level) error {
if !isValidLevel(level) {
return fmt.Errorf("invalid level: %d", level)
}
l.setLevel(level)
return nil
}
func (l *logger) SetLevelString(str string) error {
level, ok := parseLevelString(str)
if !ok {
return fmt.Errorf("invalid level string: %q", str)
}
l.setLevel(level)
return nil
}
func (l *logger) setLevel(level Level) {
l.mu.Lock()
defer l.mu.Unlock()
opts := *l.getOptions()
opts.SetLevel(level)
l.setOptions(&opts)
}
func (l *logger) Fatal(msg string, fields ...interface{}) {
l.output(1, FatalLevel, msg, fields)
}
func (l *logger) Error(msg string, fields ...interface{}) {
l.output(1, ErrorLevel, msg, fields)
}
func (l *logger) Warn(msg string, fields ...interface{}) {
l.output(1, WarnLevel, msg, fields)
}
func (l *logger) Info(msg string, fields ...interface{}) {
l.output(1, InfoLevel, msg, fields)
}
func (l *logger) Debug(msg string, fields ...interface{}) {
l.output(1, DebugLevel, msg, fields)
}
func (l *logger) Output(calldepth int, level Level, msg string, fields ...interface{}) {
if !isValidLevel(level) {
return
}
if calldepth < 0 {
calldepth = 0
}
l.output(calldepth+1, level, msg, fields)
}
func (l *logger) output(calldepth int, level Level, msg string, fields []interface{}) {
opts := l.getOptions()
if !isLevelEnabled(level, opts.level) {
return
}
location := callerLocation(calldepth + 1)
combinedFields, err := combineFields(l.fields, fields)
if err != nil {
fmt.Fprintf(ConcurrentStderr, "log: failed to combine fields, error=%v, location=%s\n", err, location)
}
pool := getBytesBufferPool()
buffer := pool.Get()
defer pool.Put(buffer)
buffer.Reset()
data, err := opts.formatter.Format(&Entry{
Location: location,
Time: time.Now(),
Level: level,
TraceId: opts.traceId,
Message: msg,
Fields: combinedFields,
Buffer: buffer,
})
if err != nil {
fmt.Fprintf(ConcurrentStderr, "log: failed to format Entry, error=%v, location=%s\n", err, location)
return
}
if _, err = opts.output.Write(data); err != nil {
fmt.Fprintf(ConcurrentStderr, "log: failed to write to log, error=%v, location=%s\n", err, location)
return
}
}
func (l *logger) WithField(key string, value interface{}) Logger {
if key == "" {
return l
}
if len(l.fields) == 0 {
nl := &logger{
fields: map[string]interface{}{key: value},
}
nl.setOptions(l.getOptions())
return nl
}
m := make(map[string]interface{}, len(l.fields)+1)
for k, v := range l.fields {
m[k] = v
}
m[key] = value
nl := &logger{
fields: m,
}
nl.setOptions(l.getOptions())
return nl
}
func (l *logger) WithFields(fields ...interface{}) Logger {
if len(fields) == 0 {
return l
}
m, err := combineFields(l.fields, fields)
if err != nil {
fmt.Fprintf(ConcurrentStderr, "log: failed to combine fields, error=%v, location=%s\n", err, callerLocation(1))
}
nl := &logger{
fields: m,
}
nl.setOptions(l.getOptions())
return nl
}