Now that we’ve made it through the Handler interface, let’s look at the first of the implementations provided by the standard library: the DiscardHandler.
var DiscardHandler Handler = discardHandler{}DiscardHandler discards all log output. DiscardHandler.Enabled returns false for all Levels.
Why would you ever want a discard handler?
Two likely scenarios come to mind.
The one where I most frequently use it, is testing. You may not wish to log anything during a test, and this is a simple way to do that:
func TestFoo(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
got, err := Foo(t.Context(), logger)
if err != nil {
t.Fatal(err)
}
if want := 42; got != want {
t.Errorf("Foo returned an unexpected value: %v", got)
}
}
The other use case would be a simple way to disable logging based on configuration or runtime state.
func initLogger() *slog.Logger {
var handler slog.Handler
if os.Getenv("DISABLE_LOGGING") != "" {
handler = slog.DiscardHandler
} else {
handler = slog.NewJSONHandler(os.Stderr, nil)
}
return slog.New(handler)
}