Source file src/log/slog/example_discard_test.go

     1  // Copyright 2024 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package slog_test
     6  
     7  import (
     8  	"log/slog"
     9  	"os"
    10  )
    11  
    12  func Example_discardHandler() {
    13  	removeTime := func(groups []string, a slog.Attr) slog.Attr {
    14  		if a.Key == slog.TimeKey && len(groups) == 0 {
    15  			return slog.Attr{}
    16  		}
    17  		return a
    18  	}
    19  	// A slog.TextHandler can output log messages.
    20  	logger1 := slog.New(slog.NewTextHandler(
    21  		os.Stdout,
    22  		&slog.HandlerOptions{ReplaceAttr: removeTime},
    23  	))
    24  	logger1.Info("message 1")
    25  
    26  	// A slog.DiscardHandler will discard all messages.
    27  	logger2 := slog.New(slog.DiscardHandler)
    28  	logger2.Info("message 2")
    29  
    30  	// Output:
    31  	// level=INFO msg="message 1"
    32  }
    33  

View as plain text