-
Notifications
You must be signed in to change notification settings - Fork 0
/
event.go
101 lines (79 loc) · 1.79 KB
/
event.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package events
import (
"fmt"
"log/slog"
"maps"
"sync"
"github.com/google/uuid"
"golang.org/x/xerrors"
)
var (
AttrDuration = "duration"
AttrError = "error"
AttrErrorCause = "errorCause"
AttrErrorStack = "errorStack"
AttrHTTPMethod = "httpMethod"
AttrHTTPRemoteAddr = "httpRemoteAddr"
AttrHTTPRespLen = "httpRespLen"
AttrHTTPRespStatus = "httpRespStatus"
AttrHTTPSourceIP = "httpSourceIp"
AttrHTTPURI = "httpUri"
AttrHTTPUserAgent = "httpUserAgent"
AttrProtocol = "protocol"
AttrRequestID = "requestId"
)
type Event struct {
attrs map[string]slog.Value
mutex sync.RWMutex
baseLogger *slog.Logger
}
func NewEvent(logger *slog.Logger) *Event {
requestID := uuid.New().String()
e := &Event{
attrs: map[string]slog.Value{},
baseLogger: logger,
}
e.SetAttr(AttrRequestID, requestID)
return e
}
func (e *Event) Clone() *Event {
e.mutex.RLock()
attrs := maps.Clone(e.attrs)
e.mutex.RUnlock()
return &Event{
attrs: attrs,
baseLogger: e.baseLogger,
}
}
func (e *Event) SetAttr(key string, value any) {
e.mutex.Lock()
e.attrs[key] = slog.AnyValue(value)
e.mutex.Unlock()
}
func (e *Event) GetAttr(key string) any {
e.mutex.RLock()
value := e.attrs[key].Any()
e.mutex.RUnlock()
return value
}
func (e *Event) SetError(err error) {
e.SetAttr(AttrError, err)
if _, ok := err.(xerrors.Wrapper); ok {
e.SetAttr(AttrErrorStack, fmt.Sprintf("%+v", err))
}
if cause, ok := GetCause(err); ok {
e.SetAttr(AttrErrorCause, fmt.Sprintf("%#v", cause))
}
}
func (e *Event) Logger() *slog.Logger {
e.mutex.RLock()
attrs := make([]any, 0, len(e.attrs))
for key, value := range e.attrs {
attrs = append(attrs, slog.Attr{
Key: key,
Value: value,
})
}
e.mutex.RUnlock()
return e.baseLogger.With(attrs...)
}