Created
November 30, 2023 09:02
-
-
Save michenriksen/ae3bc1f3a3210c5127fb7c81b8466f4c to your computer and use it in GitHub Desktop.
Helper function for stabilizing slog.Logger output during testing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NewSlogStabilizer returns a [slog.Handler] ReplaceAttr function that replaces | |
// non-deterministic attribute values with stable values. | |
// | |
// All attribute values of type [time.Time] and [time.Duration] are replaced | |
// with their zero values. | |
// | |
// Usage: | |
// | |
// logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ | |
// ReplaceAttr: NewSlogStabilizer(t) | |
// })) | |
func NewSlogStabilizer(tb testing.TB) func([]string, slog.Attr) slog.Attr { | |
tb.Helper() | |
return func(_ []string, a slog.Attr) slog.Attr { | |
tb.Helper() | |
switch a.Value.Any().(type) { | |
case time.Time: | |
return slog.Attr{Key: a.Key, Value: slog.TimeValue(time.Time{})} | |
case time.Duration: | |
return slog.Attr{Key: a.Key, Value: slog.DurationValue(time.Duration(0))} | |
default: | |
return a | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment