Source file src/log/slog/example_multi_handler_test.go

     1  // Copyright 2025 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  	"bytes"
     9  	"log/slog"
    10  	"os"
    11  )
    12  
    13  func ExampleMultiHandler() {
    14  	removeTime := func(groups []string, a slog.Attr) slog.Attr {
    15  		if a.Key == slog.TimeKey && len(groups) == 0 {
    16  			return slog.Attr{}
    17  		}
    18  		return a
    19  	}
    20  
    21  	var textBuf, jsonBuf bytes.Buffer
    22  	textHandler := slog.NewTextHandler(&textBuf, &slog.HandlerOptions{ReplaceAttr: removeTime})
    23  	jsonHandler := slog.NewJSONHandler(&jsonBuf, &slog.HandlerOptions{ReplaceAttr: removeTime})
    24  
    25  	multiHandler := slog.NewMultiHandler(textHandler, jsonHandler)
    26  	logger := slog.New(multiHandler)
    27  
    28  	logger.Info("login",
    29  		slog.String("name", "whoami"),
    30  		slog.Int("id", 42),
    31  	)
    32  
    33  	os.Stdout.WriteString(textBuf.String())
    34  	os.Stdout.WriteString(jsonBuf.String())
    35  
    36  	// Output:
    37  	// level=INFO msg=login name=whoami id=42
    38  	// {"level":"INFO","msg":"login","name":"whoami","id":42}
    39  }
    40  

View as plain text