slog.DiscardHandler

September 14, 2026

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)
}

Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


slog.Handler

I’m probably doing this in backwards order, but that’s the order the GoDoc presents it… Now that we’ve looked at each of the methods of the Handler interface, we come to its general description: type Handler A Handler handles log records produced by a Logger. A typical handler may print log records to standard error, or write them to a file or database, or perhaps augment them with additional attributes and pass them on to another handler.


slog.Handler.WithGroup

I hope everyone had a good Labor Day weekend… even if you’re not in the US and had to/got to labor on Monday. Speaking of labor, I’m looking for new clients! If you could use some world class Go expertise on your project, please reach out! type Handler type Handler interface { … // WithGroup returns a new Handler with the given group appended to // the receiver's existing groups. // The keys of all subsequent attributes, whether added by With or in a // Record, should be qualified by the sequence of group names.


slog.Handler.WithAttrs

type Handler type Handler interface { … // WithAttrs returns a new Handler whose attributes consist of // both the receiver's attributes and the arguments. // The Handler owns the slice: it may retain, modify or discard it. WithAttrs(attrs []Attr) Handler This is likely the most interesting and subtle method of the slog.Handler interface. The important thing to note is that the handler is not mutated in place. Rather, a new handler is meant to be returned.

Get daily content like this in your inbox!

Subscribe