/
handler.go
304 lines (263 loc) · 6.42 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
package log
import (
"bytes"
"context"
"fmt"
"io"
"log/slog"
"slices"
"strconv"
"sync"
"time"
"github.com/fatih/color"
"github.com/samber/lo"
"golang.org/x/xerrors"
)
const (
errKey = "err"
prefixKey = "prefix"
)
type ColorHandler struct {
opts Options
prefix string
preformatted []byte // data from WithGroup and WithAttrs
groups []string // groups from WithGroup
mu *sync.Mutex
out io.Writer
}
type Options struct {
// Level reports the minimum level to log.
// Levels with lower levels are discarded.
// If nil, the Handler uses [slog.LevelInfo].
Level slog.Leveler
}
func NewHandler(out io.Writer, opts *Options) *ColorHandler {
h := &ColorHandler{
out: out,
mu: &sync.Mutex{},
}
if opts != nil {
h.opts = *opts
}
if h.opts.Level == nil {
h.opts.Level = slog.LevelInfo
}
return h
}
func (h *ColorHandler) Enabled(_ context.Context, level slog.Level) bool {
return level >= h.opts.Level.Level()
}
func (h *ColorHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
h2 := *h
// Add an unopened group to h2 without modifying h.
h2.groups = make([]string, len(h.groups)+1)
copy(h2.groups, h.groups)
h2.groups[len(h2.groups)-1] = name
return &h2
}
func (h *ColorHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
h2 := *h
// Force an append to copy the underlying array.
h2.preformatted = slices.Clip(h.preformatted)
// Pre-format the attributes.
for _, a := range attrs {
if isLogPrefix(a) {
h2.prefix = string(a.Value.Any().(logPrefix))
continue
}
h2.preformatted = h2.appendAttr(h2.preformatted, a, h.groups)
}
return &h2
}
func (h *ColorHandler) appendAttr(buf []byte, a slog.Attr, groups []string) []byte {
// Resolve the Attr's value before doing anything else.
a.Value = a.Value.Resolve()
// Ignore empty Attrs and log prefixes.
if a.Equal(slog.Attr{}) || isLogPrefix(a) {
return buf
}
var key string
for _, g := range groups {
key += g + "."
}
key += a.Key
switch a.Value.Kind() {
case slog.KindString:
// Quote string values, to make them easy to parse.
buf = append(buf, key...)
buf = append(buf, '=')
buf = strconv.AppendQuote(buf, a.Value.String())
case slog.KindTime:
// Write times in a standard way, without the monotonic time.
buf = append(buf, key...)
buf = append(buf, '=')
buf = a.Value.Time().AppendFormat(buf, time.RFC3339Nano)
case slog.KindGroup:
attrs := a.Value.Group()
// Ignore empty groups.
if len(attrs) == 0 {
return buf
}
if a.Key != "" {
groups = append(groups, a.Key)
}
for _, ga := range attrs {
buf = h.appendAttr(buf, ga, groups)
}
buf = bytes.TrimRight(buf, " ") // Trim the trailing space.
default:
buf = append(buf, key...)
buf = append(buf, '=')
if err, ok := a.Value.Any().(error); ok {
buf = append(buf, color.HiRedString(strconv.Quote(err.Error()))...)
} else {
buf = append(buf, a.Value.String()...)
}
}
return append(buf, ' ')
}
func (h *ColorHandler) Handle(ctx context.Context, r slog.Record) error {
bufp := allocBuf()
buf := *bufp
defer func() {
*bufp = buf
freeBuf(bufp)
}()
buf = h.handle(ctx, buf, r)
h.mu.Lock()
defer h.mu.Unlock()
if _, err := h.out.Write(buf); err != nil {
return xerrors.Errorf("failed to write log: %w", err)
}
return nil
}
func (h *ColorHandler) handle(ctx context.Context, buf []byte, r slog.Record) []byte {
colorize := color.New()
switch r.Level {
case slog.LevelDebug:
colorize = colorize.Add(color.FgHiBlack)
case slog.LevelInfo:
colorize = colorize.Add(color.FgHiBlue)
case slog.LevelWarn:
colorize = colorize.Add(color.FgHiYellow)
case slog.LevelError:
colorize = colorize.Add(color.FgHiRed)
case LevelFatal:
colorize = colorize.Add(color.FgRed)
}
// Timestamp
if !r.Time.IsZero() {
buf = append(buf, r.Time.Format(time.RFC3339)...)
buf = append(buf, '\t')
}
// Level
buf = append(buf, colorize.Sprint(levelString(r.Level))...)
buf = append(buf, '\t')
// Message
buf = append(buf, h.Prefix(ctx, r)+r.Message...)
if r.Level == LevelFatal {
// Show the error and return early.
format := lo.Ternary(h.opts.Level == slog.LevelDebug, "\n - %+v\n", "\t%v\n")
return fmt.Appendf(buf, format, h.Err(r))
}
// Attrs
var preformatted []byte
for _, a := range contextualAttrs(ctx) {
preformatted = h.appendAttr(preformatted, a, h.groups)
}
preformatted = append(preformatted, h.preformatted...)
if len(preformatted) > 0 || r.NumAttrs() > 0 {
buf = append(buf, '\t')
}
if len(preformatted) > 0 {
buf = append(buf, preformatted...)
}
r.Attrs(func(a slog.Attr) bool {
buf = h.appendAttr(buf, a, h.groups)
return true
})
// Trim the trailing space.
buf = bytes.TrimRight(buf, " ")
buf = append(buf, '\n')
return buf
}
// Err returns the error from the attrs, if any.
func (h *ColorHandler) Err(r slog.Record) error {
return findKey[error](errKey, r)
}
// Prefix returns the prefix from the attrs, if any.
func (h *ColorHandler) Prefix(ctx context.Context, r slog.Record) string {
if attrPrefix := string(findKey[logPrefix](prefixKey, r)); attrPrefix != "" {
return attrPrefix
}
if ctxPrefix := contextualPrefix(ctx); ctxPrefix != "" {
return ctxPrefix
}
return h.prefix
}
func findKey[T any](key string, r slog.Record) T {
var v T
r.Attrs(func(a slog.Attr) bool {
if a.Key != key {
return true
}
var ok bool
if v, ok = a.Value.Any().(T); !ok {
return true
}
return false
})
return v
}
var (
String = slog.String
Int64 = slog.Int64
Int = slog.Int
Bool = slog.Bool
Time = slog.Time
Duration = slog.Duration
Group = slog.Group
Any = slog.Any
)
// Err returns an Attr that represents an error.
func Err(err error) slog.Attr {
return slog.Any(errKey, err)
}
type logPrefix string
// Prefix returns an Attr that represents a prefix.
func Prefix(prefix string) slog.Attr {
return slog.Any(prefixKey, logPrefix("["+prefix+"] "))
}
func isLogPrefix(a slog.Attr) bool {
_, ok := a.Value.Any().(logPrefix)
return ok
}
func levelString(level slog.Level) string {
if level == LevelFatal {
return "FATAL"
}
return level.String()
}
var bufPool = sync.Pool{
New: func() any {
b := make([]byte, 0, 1024)
return &b
},
}
func allocBuf() *[]byte {
return bufPool.Get().(*[]byte)
}
func freeBuf(b *[]byte) {
// To reduce peak allocation, return only smaller buffers to the pool.
const maxBufferSize = 16 << 10
if cap(*b) <= maxBufferSize {
*b = (*b)[:0]
bufPool.Put(b)
}
}