-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdevslog.go
99 lines (87 loc) · 2.43 KB
/
devslog.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
package devslog
import (
"context"
"fmt"
"io"
"log/slog"
"sync"
"time"
)
// A Handler handles log records produced by a Logger.
type Handler struct {
attrs []slog.Attr
groups []string
opts slog.HandlerOptions
mu *sync.Mutex
w io.Writer
}
// NewHandler creates a handler that writes to w, using the given options.
// If opts is nil, the default options are used.
func NewHandler(w io.Writer, opts *slog.HandlerOptions) *Handler {
if opts == nil {
opts = &slog.HandlerOptions{}
}
return &Handler{
w: w,
opts: *opts,
mu: &sync.Mutex{},
}
}
// Enabled reports whether the handler handles records at the given level.
// The handler ignores records whose level is lower.
func (h *Handler) Enabled(_ context.Context, level slog.Level) bool {
minLevel := slog.LevelInfo
if h.opts.Level != nil {
minLevel = h.opts.Level.Level()
}
return level >= minLevel
}
// WithAttrs returns a new handler whose attributes consists of h's attributes
// followed by attrs.
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &Handler{
attrs: append(h.attrs, attrs...),
groups: h.groups,
opts: h.opts,
mu: h.mu,
w: h.w,
}
}
// WithGroup returns a new Handler with the given group appended to
// the receiver's existing groups.
func (h *Handler) WithGroup(name string) slog.Handler {
return &Handler{
attrs: h.attrs,
groups: append(h.groups, name),
opts: h.opts,
mu: h.mu,
w: h.w,
}
}
// Handle formats its argument Record so that message is followed by each
// of it's attributes on seperate lines.
func (h *Handler) Handle(_ context.Context, r slog.Record) error {
var attrs string
for _, a := range h.attrs {
if !a.Equal(slog.Attr{}) {
attrs += gray(" ↳ " + a.Key + ": " + a.Value.String() + "\n")
}
}
r.Attrs(func(a slog.Attr) bool {
if !a.Equal(slog.Attr{}) {
attrs += gray(" ↳ " + a.Key + ": " + a.Value.String() + "\n")
}
return true
})
h.mu.Lock()
_, err := fmt.Fprintf(h.w, "%s %s %s\n%s", r.Time.Format(time.TimeOnly), text(levelColour(r.Level), r.Level.String()), r.Message, attrs)
h.mu.Unlock()
return err
}
// SetDefault is syntactic sugar for constructing a new devslog handler
// and setting it as the default [slog.Logger]. The top-level slog
// functions [slog.Info], [slog.Debug], etc will all use this handler
// to format the records.
func SetDefault(w io.Writer, opts *slog.HandlerOptions) {
slog.SetDefault(slog.New(NewHandler(w, opts)))
}