-
Notifications
You must be signed in to change notification settings - Fork 1
/
log.go
82 lines (72 loc) · 1.52 KB
/
log.go
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package igo
import (
"context"
"io"
"log/slog"
"go.opentelemetry.io/otel/trace"
)
var LogPrivacyAttrKey = []string{
"password",
"token",
"secretkey",
"accesskey",
}
// NewTraceSlogHandler 集成trace的slog handler
func NewTraceSlogHandler(w io.Writer, addSource bool, lvl slog.Leveler) slog.Handler {
sets := make(map[string]struct{})
for _, v := range LogPrivacyAttrKey {
sets[v] = struct{}{}
}
opt := slog.HandlerOptions{
Level: lvl,
AddSource: addSource,
ReplaceAttr: func(g []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.String(
slog.TimeKey,
a.Value.Time().Format("2006-01-02 15:04:05"),
)
}
if _, ok := sets[a.Key]; ok {
if a.Value.Kind() == slog.KindString {
return slog.String(a.Key, replaceLogPrivacyAttrKey(a.Value.String()))
}
}
return a
},
}
return &logTraceHandle{
slog.NewTextHandler(w, &opt),
}
}
func replaceLogPrivacyAttrKey(s string) string {
p := []rune(s)
n := len(p)
if n == 0 {
return s
}
if n < 3 {
return string(p[0]) + "*"
}
start := n / 3
for i := start; i < n-start; i++ {
p[i] = '*'
}
return string(p)
}
type logTraceHandle struct {
*slog.TextHandler
}
func (h *logTraceHandle) Handle(c context.Context, r slog.Record) error {
if id := GetTraceID(c); id != "" {
r.AddAttrs(slog.String("traceid", id))
}
return h.TextHandler.Handle(c, r)
}
func GetTraceID(c context.Context) string {
span := trace.SpanContextFromContext(c)
if span.IsValid() {
return span.TraceID().String()
}
return ""
}