| 1 |
// Copyright 2023 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
// Package benchmarks contains benchmarks for slog. |
| 6 |
// |
| 7 |
// These benchmarks are loosely based on github.com/uber-go/zap/benchmarks. |
| 8 |
// They have the following desirable properties: |
| 9 |
// |
| 10 |
// - They test a complete log event, from the user's call to its return. |
| 11 |
// |
| 12 |
// - The benchmarked code is run concurrently in multiple goroutines, to |
| 13 |
// better simulate a real server (the most common environment for structured |
| 14 |
// logs). |
| 15 |
// |
| 16 |
// - Some handlers are optimistic versions of real handlers, doing real-world |
| 17 |
// tasks as fast as possible (and sometimes faster, in that an |
| 18 |
// implementation may not be concurrency-safe). This gives us an upper bound |
| 19 |
// on handler performance, so we can evaluate the (handler-independent) core |
| 20 |
// activity of the package in an end-to-end context without concern that a |
| 21 |
// slow handler implementation is skewing the results. |
| 22 |
// |
| 23 |
// - We also test the built-in handlers, for comparison. |
| 24 |
package benchmarks |
| 25 |
|
| 26 |
import ( |
| 27 |
"errors" |
| 28 |
"log/slog" |
| 29 |
"time" |
| 30 |
) |
| 31 |
|
| 32 |
const testMessage = "Test logging, but use a somewhat realistic message length." |
| 33 |
|
| 34 |
type event struct { |
| 35 |
ID string |
| 36 |
Index int |
| 37 |
Flag bool |
| 38 |
} |
| 39 |
|
| 40 |
var ( |
| 41 |
testTime = time.Date(2022, time.May, 1, 0, 0, 0, 0, time.UTC) |
| 42 |
testString = "7e3b3b2aaeff56a7108fe11e154200dd/7819479873059528190" |
| 43 |
testInt = 32768 |
| 44 |
testDuration = 23 * time.Second |
| 45 |
testError = errors.New("fail") |
| 46 |
testEvent = event{"abcdefgh", 65536, true} |
| 47 |
) |
| 48 |
|
| 49 |
var testAttrs = []slog.Attr{ |
| 50 |
slog.String("string", testString), |
| 51 |
slog.Int("status", testInt), |
| 52 |
slog.Duration("duration", testDuration), |
| 53 |
slog.Time("time", testTime), |
| 54 |
slog.Any("error", testError), |
| 55 |
} |
| 56 |
|
| 57 |
const wantText = "time=1651363200 level=0 msg=Test logging, but use a somewhat realistic message length. string=7e3b3b2aaeff56a7108fe11e154200dd/7819479873059528190 status=32768 duration=23000000000 time=1651363200 error=fail\n" |