Source file src/log/slog/example_logvaluer_secret_test.go

     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  	"log/slog"
     9  	"os"
    10  )
    11  
    12  // A token is a secret value that grants permissions.
    13  type Token string
    14  
    15  // LogValue implements slog.LogValuer.
    16  // It avoids revealing the token.
    17  func (Token) LogValue() slog.Value {
    18  	return slog.StringValue("REDACTED_TOKEN")
    19  }
    20  
    21  // This example demonstrates a Value that replaces itself
    22  // with an alternative representation to avoid revealing secrets.
    23  func ExampleLogValuer_secret() {
    24  	t := Token("shhhh!")
    25  	removeTime := func(groups []string, a slog.Attr) slog.Attr {
    26  		if a.Key == slog.TimeKey && len(groups) == 0 {
    27  			return slog.Attr{}
    28  		}
    29  		return a
    30  	}
    31  	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: removeTime}))
    32  	logger.Info("permission granted", "user", "Perry", "token", t)
    33  
    34  	// Output:
    35  	// level=INFO msg="permission granted" user=Perry token=REDACTED_TOKEN
    36  }
    37  

View as plain text