-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
62 lines (50 loc) · 1.45 KB
/
Copy pathexample_test.go
File metadata and controls
62 lines (50 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package example
import (
"bytes"
"fmt"
"log/slog"
"github.com/alesr/redact"
)
func ExampleNewRedactionPipeline() {
// Create a buffer to capture the log output
var buf bytes.Buffer
// Create a base handler that writes to the buffer
handler := slog.NewTextHandler(&buf, &slog.HandlerOptions{
Level: slog.LevelInfo,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
// Remove the time attribute
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
})
// Create a redaction pipeline
pipeline := redact.NewRedactionPipeline()
pipeline.AddRedactField("email")
pipeline.AddRedactField("password")
// Create a RedactionHandler that wraps the original handler
redactionHandler := redact.NewRedactionHandler(handler, pipeline)
// Create a logger with the RedactionHandler
logger := slog.New(redactionHandler)
buf.Reset()
logger.Info(
"Test message",
slog.String("username", "Rigoletto"),
slog.String("email", "foo@bar.qux"),
slog.String("password", "abc123"),
slog.Int("other_field", 456),
)
// Without type attr
logger.Info(
"Test message",
"username", "Rigoletto",
"email", "foo@bar.qux",
"password", "abc123",
"other_field", 456,
)
output := buf.String()
fmt.Print(output)
// Output: level=INFO msg="Test message" username=Rigoletto email=[REDACTED] password=[REDACTED] other_field=456
// level=INFO msg="Test message" username=Rigoletto email=[REDACTED] password=[REDACTED] other_field=456
}