-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
88 lines (69 loc) · 1.9 KB
/
Copy pathhandler.go
File metadata and controls
88 lines (69 loc) · 1.9 KB
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
package clog
import (
"context"
"fmt"
"io"
"log/slog"
"path"
"runtime"
"strings"
"sync"
)
// Handler implements an slog.Handler.
type Handler struct {
mutex sync.Mutex
opts HandlerOptions
colorOpts ColorOptions
formatOpts FormatOptions
writer io.Writer
attrs []slog.Attr
groups []string
}
var _ slog.Handler = new(Handler) // Handle implements the slog.Handler interface.
// Enabled implements the slog.Handler interface.
func (h *Handler) Enabled(_ context.Context, l slog.Level) bool {
minLevel := slog.LevelInfo
if h.opts.Level != nil {
minLevel = h.opts.Level.Level()
}
return l >= minLevel
}
// Handle implements the slog.Handler interface.
func (h *Handler) Handle(_ context.Context, rec slog.Record) error { //nolint:gocritic
c := h.colorOpts.Colorer
msg := new(strings.Builder)
fmt.Fprint(msg, c.Color(rec.Time.Format(h.formatOpts.Time), h.colorOpts.Time),
" ", c.Color(h.formatOpts.levelString(rec.Level), h.colorOpts.levelColor(rec.Level)),
" ", rec.Message)
if h.opts.AddSource {
fs := runtime.CallersFrames([]uintptr{rec.PC})
f, _ := fs.Next()
src := fmt.Sprint("[", path.Base(f.File), ":", f.Line, "]")
fmt.Fprint(msg, " ", c.Color(src, h.colorOpts.Source))
}
for i := range h.attrs {
key, val := h.attrFmt(rec.Level, h.attrs[i])
fmt.Fprint(msg, " ", key, val)
}
rec.Attrs(func(attr slog.Attr) bool {
key, val := h.attrFmt(rec.Level, attr)
fmt.Fprint(msg, " ", key, val)
return true
})
h.mutex.Lock()
defer h.mutex.Unlock()
fmt.Fprintln(h.writer, msg.String())
return nil
}
// WithAttrs implements the slog.Handler interface.
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
h2 := h.clone()
h2.attrs = append(h2.attrs, attrs...)
return h2
}
// WithGroup implements the slog.Handler interface.
func (h *Handler) WithGroup(name string) slog.Handler {
h2 := h.clone()
h2.groups = append(h2.groups, name)
return h2
}