Files
summercms/modules/sunscreen/example_test.go

83 lines
2.4 KiB
Go

package sunscreen_test
import (
"bytes"
"errors"
"io"
"log"
"log/slog"
"os"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/sunscreen"
)
func ExampleWrap() {
// Drop the time so the output is stable; a real application keeps it.
plain := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if len(groups) == 0 && a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
})
logger := slog.New(sunscreen.Wrap(plain))
logger.Info("vendor call failed",
"api_key", "live-key-123",
slog.Group("request", slog.String("Authorization", "Bearer abc.def")),
"err", errors.New("401 for key sk-abcdefghijklmnopqrstuvwx"),
)
// Output:
// level=INFO msg="vendor call failed" api_key=[REDACTED] request.Authorization=[REDACTED] err="401 for key sk-[REDACTED]"
}
func ExampleWrap_json() {
// Drop the time so the output is stable; a real application keeps it.
opts := &slog.HandlerOptions{ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if len(groups) == 0 && a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
}}
key, err := "live-key-123", errors.New("401 Unauthorized")
logger := slog.New(sunscreen.Wrap(slog.NewJSONHandler(os.Stdout, opts)))
logger.Error("vendor call failed", "api_key", key, "err", err)
// Output:
// {"level":"ERROR","msg":"vendor call failed","api_key":"[REDACTED]","err":"401 Unauthorized"}
}
// startLogging is the first thing the main function of a program that does
// not use diary runs; main passes os.Stderr.
func startLogging(stderr io.Writer) {
sunscreen.InstallDefault(stderr)
slog.Info("starting", "token", "abc123")
log.Print("calling the vendor with Authorization: Bearer abc.def")
}
// TestDocsInstallDefault runs startLogging into a buffer and restores the
// process default logger and the log package afterwards.
func TestDocsInstallDefault(t *testing.T) {
previous, out, flags := slog.Default(), log.Writer(), log.Flags()
t.Cleanup(func() {
slog.SetDefault(previous)
log.SetOutput(out)
log.SetFlags(flags)
})
var buf bytes.Buffer
startLogging(&buf)
got := buf.String()
for _, want := range []string{`msg=starting token=[REDACTED]`, `Authorization: Bearer [REDACTED]`} {
if !strings.Contains(got, want) {
t.Errorf("output %q lacks %q", got, want)
}
}
if strings.Contains(got, "abc123") || strings.Contains(got, "abc.def") {
t.Errorf("output leaks a secret: %q", got)
}
}