Skip to content

Commit

Permalink
apply fix to golang/go#61774
Browse files Browse the repository at this point in the history
  • Loading branch information
vikstrous committed Aug 8, 2023
1 parent 2a1222a commit 693711e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
14 changes: 12 additions & 2 deletions testerrorer/testerrorer.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,21 @@ type testErrorer struct {
Next func(groups []string, a slog.Attr) slog.Attr
}

var levelNames = map[slog.Level]slog.Value{
slog.LevelDebug: slog.StringValue("DEBUG"),
slog.LevelInfo: slog.StringValue("INFO"), // default
slog.LevelError: slog.StringValue("ERROR"),
slog.LevelWarn: slog.StringValue("WARN"),
}

func (t *testErrorer) replaceAttr(groups []string, a slog.Attr) slog.Attr {
if a.Value.Kind() == slog.KindAny {
level, ok := a.Value.Any().(slog.Level)
if ok && level >= slog.LevelError {
t.TB.Errorf("An error was logged.")
if ok {
a.Value = levelNames[level]
if level >= slog.LevelError {
t.TB.Errorf("An error was logged.")
}
}
}
if t.Next == nil {
Expand Down
8 changes: 3 additions & 5 deletions testerrorer/testerrorer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,14 @@ func TestErrorerCallsNext(t *testing.T) {

func TestErrorerErrors(t *testing.T) {
wrappedT := &TestT{T: t}
logger := slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{
logger := slog.New(slog.NewJSONHandler(io.Discard, &slog.HandlerOptions{
ReplaceAttr: testerrorer.NewTestErrorer(wrappedT, nil),
}))
ctx := context.Background()
allocsPerRun := testing.AllocsPerRun(1, func() {
logger.InfoContext(ctx, "example")
})
if allocsPerRun > 1 {
// There's one allocation that we can't avoid. https://github.com/golang/go/issues/61774
if allocsPerRun > 0 {
t.Fatalf("extra allocations introduced in info path %.0f", allocsPerRun)
}
if wrappedT.DidError {
Expand All @@ -56,8 +55,7 @@ func TestErrorerErrors(t *testing.T) {
if !wrappedT.DidError {
t.Fatal("did not error at error level")
}
if allocsPerRun > 1 {
// There's one allocation that we can't avoid. https://github.com/golang/go/issues/61774
if allocsPerRun > 0 {
t.Fatalf("extra allocations introduced in error path: %.0f", allocsPerRun)
}
wrappedT.DidError = false
Expand Down

0 comments on commit 693711e

Please sign in to comment.