forked from btcsuite/btclog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
434 lines (384 loc) · 9.51 KB
/
handler.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
package btclog
import (
"context"
"fmt"
"io"
"log/slog"
"strconv"
"sync"
"sync/atomic"
"time"
"unicode"
"unicode/utf8"
)
// HandlerOption is the signature of a functional option that can be used to
// modify the behaviour of the DefaultHandler.
type HandlerOption func(*handlerOpts)
// handlerOpts holds options that can be modified by a HandlerOption.
type handlerOpts struct {
flag uint32
withTimestamp bool
styled bool
timeSource func() time.Time
}
// defaultHandlerOpts constructs a handlerOpts with default settings.
func defaultHandlerOpts() *handlerOpts {
return &handlerOpts{
flag: defaultFlags,
withTimestamp: true,
styled: false,
}
}
// WithTimeSource can be used to overwrite the time sourced from the slog
// Record.
func WithTimeSource(fn func() time.Time) HandlerOption {
return func(opts *handlerOpts) {
opts.timeSource = fn
}
}
// WithCallerFlags can be used to overwrite the default caller flag option.
func WithCallerFlags(flags uint32) HandlerOption {
return func(b *handlerOpts) {
b.flag = flags
}
}
// WithNoTimestamp is an option that can be used to omit timestamps from the log
// lines.
func WithNoTimestamp() HandlerOption {
return func(opts *handlerOpts) {
opts.withTimestamp = false
}
}
// DefaultHandler is a Handler that can be used along with NewSLogger to
// instantiate a structured logger.
type DefaultHandler struct {
opts *handlerOpts
level int64
tag string
fields []slog.Attr
callstackOffset bool
flag uint32
buf *buffer
mu *sync.Mutex
w io.Writer
}
// A compile-time check to ensure that DefaultHandler implements Handler.
var _ Handler = (*DefaultHandler)(nil)
// Level returns the current logging level of the Handler.
//
// NOTE: This is part of the Handler interface.
func (d *DefaultHandler) Level() Level {
return Level(atomic.LoadInt64(&d.level))
}
// SetLevel changes the logging level of the Handler to the passed
// level.
//
// NOTE: This is part of the Handler interface.
func (d *DefaultHandler) SetLevel(level Level) {
atomic.StoreInt64(&d.level, int64(level))
}
// NewDefaultHandler creates a new Handler that can be used along with
// NewSLogger to instantiate a structured logger.
func NewDefaultHandler(w io.Writer, options ...HandlerOption) *DefaultHandler {
opts := defaultHandlerOpts()
for _, o := range options {
o(opts)
}
return &DefaultHandler{
w: w,
level: int64(LevelInfo),
opts: opts,
buf: newBuffer(),
mu: &sync.Mutex{},
}
}
// Enabled reports whether the handler handles records at the given level.
//
// NOTE: this is part of the slog.Handler interface.
func (d *DefaultHandler) Enabled(_ context.Context, level slog.Level) bool {
return atomic.LoadInt64(&d.level) <= int64(level)
}
// Handle handles the Record. It will only be called if Enabled returns true.
//
// NOTE: this is part of the slog.Handler interface.
func (d *DefaultHandler) Handle(_ context.Context, r slog.Record) error {
buf := newBuffer()
defer buf.free()
// Timestamp.
if d.opts.withTimestamp {
// First check if the options provided specified a different
// time source to use. Otherwise, use the provided record time.
if d.opts.timeSource != nil {
writeTimestamp(buf, d.opts.timeSource())
} else if !r.Time.IsZero() {
writeTimestamp(buf, r.Time)
}
}
// Level.
d.writeLevel(buf, Level(r.Level))
// Sub-system tag.
if d.tag != "" {
buf.writeString(" " + d.tag)
}
// The call-site.
if d.opts.flag&(Lshortfile|Llongfile) != 0 {
skip := 6
if d.callstackOffset {
skip = 4
}
file, line := callsite(d.opts.flag, skip)
d.writeCallSite(buf, file, line)
}
// Finish off the header.
buf.writeString(": ")
// Write the log message itself.
if r.Message != "" {
buf.writeString(r.Message)
}
// Append logger fields.
for _, attr := range d.fields {
d.appendAttr(buf, attr)
}
// Append slog attributes.
r.Attrs(func(a slog.Attr) bool {
d.appendAttr(buf, a)
return true
})
buf.writeByte('\n')
d.mu.Lock()
defer d.mu.Unlock()
_, err := d.w.Write(*buf)
return err
}
// WithAttrs returns a new Handler with the given attributes added.
//
// NOTE: this is part of the slog.Handler interface.
func (d *DefaultHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return d.with(d.tag, true, attrs...)
}
// WithGroup returns a new Handler with the given group appended to
// the receiver's existing groups. All this implementation does is add to the
// existing tag used for the logger.
//
// NOTE: this is part of the slog.Handler interface.
func (d *DefaultHandler) WithGroup(name string) slog.Handler {
if d.tag != "" {
name = d.tag + "." + name
}
return d.with(name, true)
}
// SubSystem returns a copy of the given handler but with the new tag. All
// attributes added with WithAttrs will be kept but all groups added with
// WithGroup are lost.
//
// NOTE: this is part of the Handler interface.
func (d *DefaultHandler) SubSystem(tag string) Handler {
return d.with(tag, false)
}
// with returns a new logger with the given attributes added.
// withCallstackOffset should be false if the caller returns a concrete
// DefaultHandler and true if the caller returns the Handler interface.
func (d *DefaultHandler) with(tag string, withCallstackOffset bool,
attrs ...slog.Attr) *DefaultHandler {
d.mu.Lock()
sl := *d
d.mu.Unlock()
sl.buf = newBuffer()
sl.mu = &sync.Mutex{}
sl.fields = append(
make([]slog.Attr, 0, len(d.fields)+len(attrs)), d.fields...,
)
sl.fields = append(sl.fields, attrs...)
sl.callstackOffset = withCallstackOffset
sl.tag = tag
return &sl
}
func (d *DefaultHandler) appendAttr(buf *buffer, a slog.Attr) {
// Resolve the Attr's value before doing anything else.
a.Value = a.Value.Resolve()
// Ignore empty Attrs.
if a.Equal(slog.Attr{}) {
return
}
d.appendKey(buf, a.Key)
appendValue(buf, a.Value)
}
func (d *DefaultHandler) writeLevel(buf *buffer, level Level) {
str := fmt.Sprintf("[%s]", level)
buf.writeString(str)
}
func (d *DefaultHandler) writeCallSite(buf *buffer, file string, line int) {
if file == "" {
return
}
buf.writeString(fmt.Sprintf(" %s:%d", file, line))
}
func appendString(buf *buffer, str string) {
if needsQuoting(str) {
*buf = strconv.AppendQuote(*buf, str)
} else {
buf.writeString(str)
}
}
func (d *DefaultHandler) appendKey(buf *buffer, key string) {
buf.writeString(" ")
if needsQuoting(key) {
key = strconv.Quote(key)
}
key += "="
buf.writeString(key)
}
func appendValue(buf *buffer, v slog.Value) {
defer func() {
// Recovery in case of nil pointer dereferences.
if r := recover(); r != nil {
// Catch any panics that are most likely due to nil
// pointers.
appendString(buf, fmt.Sprintf("!PANIC: %v", r))
}
}()
appendTextValue(buf, v)
}
func appendTextValue(buf *buffer, v slog.Value) {
switch v.Kind() {
case slog.KindString:
appendString(buf, v.String())
case slog.KindAny:
appendString(buf, fmt.Sprintf("%+v", v.Any()))
default:
appendString(buf, fmt.Sprintf("%s", v))
}
}
// Copied from log/slog/text_handler.go.
//
// needsQuoting returns true if the given strings should be wrapped in quotes.
func needsQuoting(s string) bool {
if len(s) == 0 {
return true
}
for i := 0; i < len(s); {
b := s[i]
if b < utf8.RuneSelf {
// Quote anything except a backslash that would need
// quoting in a JSON string, as well as space and '='.
if b != '\\' && (b == ' ' || b == '=' || !safeSet[b]) {
return true
}
i++
continue
}
r, size := utf8.DecodeRuneInString(s[i:])
if r == utf8.RuneError || unicode.IsSpace(r) ||
!unicode.IsPrint(r) {
return true
}
i += size
}
return false
}
// Copied from encoding/json/tables.go.
//
// safeSet holds the value true if the ASCII character with the given array
// position can be represented inside a JSON string without any further
// escaping.
//
// All values are true except for the ASCII control characters (0-31), the
// double quote ("), and the backslash character ("\").
var safeSet = [utf8.RuneSelf]bool{
' ': true,
'!': true,
'"': false,
'#': true,
'$': true,
'%': true,
'&': true,
'\'': true,
'(': true,
')': true,
'*': true,
'+': true,
',': true,
'-': true,
'.': true,
'/': true,
'0': true,
'1': true,
'2': true,
'3': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
'9': true,
':': true,
';': true,
'<': true,
'=': true,
'>': true,
'?': true,
'@': true,
'A': true,
'B': true,
'C': true,
'D': true,
'E': true,
'F': true,
'G': true,
'H': true,
'I': true,
'J': true,
'K': true,
'L': true,
'M': true,
'N': true,
'O': true,
'P': true,
'Q': true,
'R': true,
'S': true,
'T': true,
'U': true,
'V': true,
'W': true,
'X': true,
'Y': true,
'Z': true,
'[': true,
'\\': false,
']': true,
'^': true,
'_': true,
'`': true,
'a': true,
'b': true,
'c': true,
'd': true,
'e': true,
'f': true,
'g': true,
'h': true,
'i': true,
'j': true,
'k': true,
'l': true,
'm': true,
'n': true,
'o': true,
'p': true,
'q': true,
'r': true,
's': true,
't': true,
'u': true,
'v': true,
'w': true,
'x': true,
'y': true,
'z': true,
'{': true,
'|': true,
'}': true,
'~': true,
'\u007f': true,
}