-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
converter.go
66 lines (52 loc) · 1.67 KB
/
converter.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
package slognats
import (
"net/http"
"log/slog"
slogcommon "github.com/samber/slog-common"
)
var SourceKey = "source"
var ContextKey = "extra"
var RequestKey = "request"
var ErrorKeys = []string{"error", "err"}
var RequestIgnoreHeaders = false
type Converter func(addSource bool, replaceAttr func(groups []string, a slog.Attr) slog.Attr, loggerAttr []slog.Attr, groups []string, record *slog.Record) any
func DefaultConverter(addSource bool, replaceAttr func(groups []string, a slog.Attr) slog.Attr, loggerAttr []slog.Attr, groups []string, record *slog.Record) any {
// aggregate all attributes
attrs := slogcommon.AppendRecordAttrsToAttrs(loggerAttr, groups, record)
// developer formatters
if addSource {
attrs = append(attrs, slogcommon.Source(SourceKey, record))
}
attrs = slogcommon.ReplaceAttrs(replaceAttr, []string{}, attrs...)
attrs = slogcommon.RemoveEmptyAttrs(attrs)
// handler formatter
extra := slogcommon.AttrsToMap(attrs...)
payload := map[string]any{
"logger.name": name,
"logger.version": version,
"timestamp": record.Time.UTC(),
"level": record.Level.String(),
"message": record.Message,
}
for _, errorKey := range ErrorKeys {
if v, ok := extra[errorKey]; ok {
if err, ok := v.(error); ok {
payload[errorKey] = slogcommon.FormatError(err)
delete(extra, errorKey)
break
}
}
}
if v, ok := extra[RequestKey]; ok {
if req, ok := v.(*http.Request); ok {
payload[RequestKey] = slogcommon.FormatRequest(req, RequestIgnoreHeaders)
delete(extra, RequestKey)
}
}
if user, ok := extra["user"]; ok {
payload["user"] = user
delete(extra, "user")
}
payload[ContextKey] = extra
return payload
}