github.com/searKing/golang/go@v1.2.117/log/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 6 7 import ( 8 "fmt" 9 "log/slog" 10 "os" 11 12 "github.com/searKing/golang/go/log/slog/internal/slogtest" 13 ) 14 15 // A token is a secret value that grants permissions. 16 type Token string 17 18 // LogValue implements slog.LogValuer. 19 // It avoids revealing the token. 20 func (Token) LogValue() slog.Value { 21 return slog.StringValue("REDACTED_TOKEN") 22 } 23 24 // This example demonstrates a Value that replaces itself 25 // with an alternative representation to avoid revealing secrets. 26 func ExampleLogValuer_secret() { 27 getPid = func() int { return 0 } // set pid to zero for test 28 defer func() { getPid = os.Getpid }() 29 t := Token("shhhh!") 30 { 31 fmt.Printf("----text----\n") 32 logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime})) 33 logger.Info("permission granted", "user", "Perry", "token", t) 34 } 35 { 36 fmt.Printf("----glog----\n") 37 logger := slog.New(NewGlogHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime})) 38 logger.Info("permission granted", "user", "Perry", "token", t) 39 } 40 { 41 fmt.Printf("----glog_human----\n") 42 logger := slog.New(NewGlogHumanHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime})) 43 logger.Info("permission granted", "user", "Perry", "token", t) 44 } 45 46 // Output: 47 // ----text---- 48 // level=INFO msg="permission granted" user=Perry token=REDACTED_TOKEN 49 // ----glog---- 50 // I 0] permission granted, user=Perry, token=REDACTED_TOKEN 51 // ----glog_human---- 52 // [INFO ] [0] permission granted, user=Perry, token=REDACTED_TOKEN 53 }