Repository navigation
Expand file tree
/
Copy pathhandler_bench_test.go
More file actions
333 lines (299 loc) · 8.21 KB
/
Copy pathhandler_bench_test.go
File metadata and controls
333 lines (299 loc) · 8.21 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
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
package slogbox
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"strconv"
"testing"
"time"
)
func BenchmarkHandle(b *testing.B) {
h := New(1024, nil)
ctx := b.Context()
r := slog.NewRecord(time.Now(), slog.LevelInfo, "benchmark", 0)
r.AddAttrs(slog.String("key", "value"))
b.ReportAllocs()
for b.Loop() {
_ = h.Handle(ctx, r)
}
}
func BenchmarkHandle_Parallel(b *testing.B) {
h := New(1024, nil)
ctx := b.Context()
r := slog.NewRecord(time.Now(), slog.LevelInfo, "benchmark", 0)
r.AddAttrs(slog.String("key", "value"))
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() { // b.Loop() is not applicable inside RunParallel; pb.Next() is correct here
_ = h.Handle(ctx, r)
}
})
}
func BenchmarkRecords(b *testing.B) {
h := New(1000, nil)
ctx := b.Context()
for range 1000 {
r := slog.NewRecord(time.Now(), slog.LevelInfo, "fill", 0)
r.AddAttrs(slog.String("k", "v"))
_ = h.Handle(ctx, r)
}
b.ReportAllocs()
for b.Loop() {
_ = h.Records()
}
}
func BenchmarkAll(b *testing.B) {
h := New(1000, nil)
ctx := b.Context()
for range 1000 {
r := slog.NewRecord(time.Now(), slog.LevelInfo, "fill", 0)
r.AddAttrs(slog.String("k", "v"))
_ = h.Handle(ctx, r)
}
b.ReportAllocs()
for b.Loop() {
for range h.All() {
}
}
}
func BenchmarkJSON(b *testing.B) {
for _, records := range jsonBenchmarkSizes {
b.Run("records="+strconv.Itoa(records), func(b *testing.B) {
h := newJSONBenchmarkHandler(b, records)
preflight, err := h.JSON()
if err != nil {
b.Fatalf("JSON preflight: %v", err)
}
validateBenchmarkJSON(b, preflight, records)
wantBytes := len(preflight)
b.SetBytes(int64(wantBytes))
b.ReportAllocs()
var output []byte
for b.Loop() {
output, err = h.JSON()
if err != nil {
b.Fatalf("JSON: %v", err)
}
if len(output) != wantBytes {
b.Fatalf("JSON wrote %d bytes, want %d", len(output), wantBytes)
}
}
validateBenchmarkJSON(b, output, records)
})
}
}
func BenchmarkWithAttrs(b *testing.B) {
h := New(1024, nil)
attrs := []slog.Attr{
slog.String("service", "api"),
slog.String("version", "1.0"),
slog.Int("port", 8080),
slog.Bool("debug", false),
slog.String("env", "prod"),
}
b.ReportAllocs()
for b.Loop() {
_ = h.WithAttrs(attrs)
}
}
func BenchmarkWithGroup(b *testing.B) {
h := New(1024, nil)
b.ReportAllocs()
for b.Loop() {
_ = h.WithGroup("request")
}
}
// discardHandler is a no-op slog.Handler for benchmarking flush overhead.
type discardHandler struct{}
func (discardHandler) Enabled(context.Context, slog.Level) bool { return true }
func (discardHandler) Handle(context.Context, slog.Record) error { return nil }
func (discardHandler) WithAttrs([]slog.Attr) slog.Handler { return discardHandler{} }
func (discardHandler) WithGroup(string) slog.Handler { return discardHandler{} }
func BenchmarkHandle_WithFlush(b *testing.B) {
// Measure overhead of flush check on the hot path (INFO, no trigger).
h := New(1024, &Options{
FlushOn: slog.LevelError,
FlushTo: discardHandler{},
})
ctx := b.Context()
r := slog.NewRecord(time.Now(), slog.LevelInfo, "benchmark", 0)
r.AddAttrs(slog.String("key", "value"))
b.ReportAllocs()
for b.Loop() {
_ = h.Handle(ctx, r)
}
}
func BenchmarkHandle_FlushTrigger(b *testing.B) {
// Cost when flush fires (ERROR, ~100 records flushed).
h := New(1024, &Options{
FlushOn: slog.LevelError,
FlushTo: discardHandler{},
})
ctx := b.Context()
info := slog.NewRecord(time.Now(), slog.LevelInfo, "fill", 0)
info.AddAttrs(slog.String("key", "value"))
errRec := slog.NewRecord(time.Now(), slog.LevelError, "boom", 0)
errRec.AddAttrs(slog.String("key", "value"))
b.ReportAllocs()
for b.Loop() {
// Write 99 INFO records then 1 ERROR to trigger flush of 100.
for range 99 {
_ = h.Handle(ctx, info)
}
_ = h.Handle(ctx, errRec)
}
}
func BenchmarkWriteTo(b *testing.B) {
for _, records := range jsonBenchmarkSizes {
b.Run("records="+strconv.Itoa(records), func(b *testing.B) {
h := newJSONBenchmarkHandler(b, records)
var preflight bytes.Buffer
written, err := h.WriteTo(&preflight)
if err != nil {
b.Fatalf("WriteTo preflight: %v", err)
}
if written != int64(preflight.Len()) {
b.Fatalf("WriteTo preflight count = %d, wrote %d bytes", written, preflight.Len())
}
validateBenchmarkJSON(b, preflight.Bytes(), records)
wantBytes := preflight.Len()
b.Run("writer=discard", func(b *testing.B) {
b.SetBytes(int64(wantBytes))
b.ReportAllocs()
for b.Loop() {
written, err := h.WriteTo(io.Discard)
if err != nil {
b.Fatalf("WriteTo: %v", err)
}
if written != int64(wantBytes) {
b.Fatalf("WriteTo count = %d, want %d", written, wantBytes)
}
}
})
b.Run("writer=buffer_reused", func(b *testing.B) {
var output bytes.Buffer
output.Grow(wantBytes)
b.SetBytes(int64(wantBytes))
b.ReportAllocs()
for b.Loop() {
output.Reset()
written, err := h.WriteTo(&output)
if err != nil {
b.Fatalf("WriteTo: %v", err)
}
if written != int64(wantBytes) || output.Len() != wantBytes {
b.Fatalf("WriteTo returned %d and wrote %d bytes, want %d", written, output.Len(), wantBytes)
}
}
validateBenchmarkJSON(b, output.Bytes(), records)
})
})
}
}
var jsonBenchmarkSizes = [...]int{1, 100, 10000}
var jsonBenchmarkTime = time.Date(2026, time.August, 22, 12, 34, 56, 789, time.UTC)
func newJSONBenchmarkHandler(b *testing.B, records int) *Handler {
b.Helper()
h := New(max(1, records), nil)
for range records {
r := slog.NewRecord(jsonBenchmarkTime, slog.LevelInfo, "msg", 0)
r.AddAttrs(
slog.String("method", "GET"),
slog.Int("status", 200),
slog.Duration("latency", 42*time.Millisecond),
slog.String("path", "/api/v1/users"),
slog.String("ip", "10.0.0.1"),
)
if err := h.Handle(b.Context(), r); err != nil {
b.Fatalf("Handle fixture record: %v", err)
}
}
return h
}
type jsonBenchmarkEntry struct {
Time time.Time `json:"time"`
Level string `json:"level"`
Message string `json:"msg"`
Attrs struct {
Method string `json:"method"`
Status int64 `json:"status"`
Latency int64 `json:"latency"`
Path string `json:"path"`
IP string `json:"ip"`
} `json:"attrs"`
}
func validateBenchmarkJSON(b *testing.B, data []byte, wantEntries int) {
b.Helper()
if !json.Valid(data) {
b.Fatalf("output is not valid JSON: %q", data)
}
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
var entries []jsonBenchmarkEntry
if err := dec.Decode(&entries); err != nil {
b.Fatalf("decode benchmark output: %v", err)
}
if err := consumeJSONEOF(dec); err != nil {
b.Fatalf("decode trailing benchmark output: %v", err)
}
if len(entries) != wantEntries {
b.Fatalf("benchmark output has %d entries, want %d", len(entries), wantEntries)
}
for i, entry := range entries {
if !entry.Time.Equal(jsonBenchmarkTime) ||
entry.Level != slog.LevelInfo.String() ||
entry.Message != "msg" ||
entry.Attrs.Method != "GET" ||
entry.Attrs.Status != 200 ||
entry.Attrs.Latency != (42*time.Millisecond).Nanoseconds() ||
entry.Attrs.Path != "/api/v1/users" ||
entry.Attrs.IP != "10.0.0.1" {
b.Fatalf("benchmark output entry %d does not match fixture: %+v", i, entry)
}
}
}
func consumeJSONEOF(dec *json.Decoder) error {
var trailing any
err := dec.Decode(&trailing)
if err == io.EOF {
return nil
}
if err == nil {
return errors.New("unexpected second JSON value")
}
return err
}
func BenchmarkFlush(b *testing.B) {
h := New(1024, &Options{
FlushOn: slog.LevelError,
FlushTo: discardHandler{},
})
ctx := b.Context()
info := slog.NewRecord(time.Now(), slog.LevelInfo, "fill", 0)
info.AddAttrs(slog.String("key", "value"))
b.ReportAllocs()
for b.Loop() {
// Write 100 INFO records, then flush explicitly.
for range 100 {
_ = h.Handle(ctx, info)
}
_ = h.Flush(ctx)
}
}
func BenchmarkRecords_WithMaxAge(b *testing.B) {
h := New(1000, &Options{MaxAge: 5 * time.Minute})
ctx := b.Context()
now := time.Now()
for i := range 1000 {
r := slog.NewRecord(now.Add(-time.Duration(1000-i)*time.Second), slog.LevelInfo, "fill", 0)
r.AddAttrs(slog.String("k", "v"))
_ = h.Handle(ctx, r)
}
b.ReportAllocs()
for b.Loop() {
_ = h.Records()
}
}