Skip to content

Instantly share code, notes, and snippets.

@michenriksen
Created November 30, 2023 09:02
Show Gist options
  • Save michenriksen/ae3bc1f3a3210c5127fb7c81b8466f4c to your computer and use it in GitHub Desktop.
Save michenriksen/ae3bc1f3a3210c5127fb7c81b8466f4c to your computer and use it in GitHub Desktop.
Helper function for stabilizing slog.Logger output during testing.
// 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