golang.org/x/exp@v0.0.0-20240506185415-9bf2ced13842/slog/example_logvaluer_secret_test.go (about)

     1  // Copyright 2022 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  	"os"
     9  
    10  	"golang.org/x/exp/slog"
    11  	"golang.org/x/exp/slog/internal/testutil"
    12  )
    13  
    14  // A token is a secret value that grants permissions.
    15  type Token string
    16  
    17  // LogValue implements slog.LogValuer.
    18  // It avoids revealing the token.
    19  func (Token) LogValue() slog.Value {
    20  	return slog.StringValue("REDACTED_TOKEN")
    21  }
    22  
    23  // This example demonstrates a Value that replaces itself
    24  // with an alternative representation to avoid revealing secrets.
    25  func ExampleLogValuer_secret() {
    26  	t := Token("shhhh!")
    27  	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: testutil.RemoveTime}))
    28  	logger.Info("permission granted", "user", "Perry", "token", t)
    29  
    30  	// Output:
    31  	// level=INFO msg="permission granted" user=Perry token=REDACTED_TOKEN
    32  }