/
log_handler.go
131 lines (116 loc) · 2.43 KB
/
log_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
package srvtest
// mostly copied from https://github.com/jba/slog/blob/main/handlers/simple/simple_handler.go
import (
"context"
"fmt"
"log/slog"
"slices"
"strconv"
"testing"
"unicode"
"unicode/utf8"
"github.com/jba/slog/withsupport"
)
type LoggerOption func(*testHandler)
func WithErrorStrategy(es ErrorStrategy) LoggerOption {
return func(th *testHandler) {
th.es = es
}
}
type testHandler struct {
t *testing.T
es ErrorStrategy
goa *withsupport.GroupOrAttrs
}
func newHandler(t *testing.T, options ...LoggerOption) slog.Handler {
th := &testHandler{
t: t,
}
for _, o := range options {
o(th)
}
return th
}
func (h *testHandler) Enabled(ctx context.Context, l slog.Level) bool {
return true
}
func (h *testHandler) WithGroup(name string) slog.Handler {
h2 := *h
h2.goa = h2.goa.WithGroup(name)
return &h2
}
func (h *testHandler) WithAttrs(as []slog.Attr) slog.Handler {
h2 := *h
h2.goa = h2.goa.WithAttrs(as)
return &h2
}
func (h *testHandler) Handle(ctx context.Context, r slog.Record) error {
r2 := slog.NewRecord(r.Time, r.Level, r.Message, r.PC)
var attrs []slog.Attr
r.Attrs(func(a slog.Attr) bool { attrs = append(attrs, a); return true })
for g := h.goa; g != nil; g = g.Next {
if g.Group != "" {
anys := make([]any, len(attrs))
for i, a := range attrs {
anys[i] = a
}
attrs = []slog.Attr{slog.Group(g.Group, anys...)}
} else {
attrs = append(slices.Clip(g.Attrs), attrs...)
}
}
r2.AddAttrs(attrs...)
h.tlog(r2)
return nil
}
func (h *testHandler) tlog(r slog.Record) {
msg := []byte{}
fmt.Append(msg, r.Level.String()+":", r.Message)
r.Attrs(func(a slog.Attr) bool {
printattr(&msg, a)
return true
})
h.t.Log(string(msg))
switch h.es {
case Fail:
h.t.Fail()
case FailNow:
h.t.FailNow()
}
}
func printattr(msg *[]byte, a slog.Attr) {
rv := a.Value.Resolve()
if rv.Kind() == slog.KindGroup {
fmt.Append(*msg, qs(a.Key)+"[")
for _, ga := range rv.Group() {
printattr(msg, ga)
}
fmt.Append(*msg, "]")
return
}
fmt.Append(*msg, qs(a.Key)+":", qs(a.Value.String()))
}
func qs(s string) string {
if needsQuoted(s) {
return strconv.Quote(s)
}
return s
}
func needsQuoted(str string) bool {
for len(str) > 0 {
if str[0] < utf8.RuneSelf {
switch str[0] {
case '\n', '\t', ' ':
return true
}
str = str[1:]
continue
}
r, size := utf8.DecodeRuneInString(str)
if unicode.IsSpace(r) {
return true
}
str = str[size:]
}
return false
}