-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
converter.go
85 lines (72 loc) · 2.3 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package slogdatadog
import (
"reflect"
"log/slog"
slogcommon "github.com/samber/slog-common"
)
var SourceKey = "source"
var ErrorKeys = []string{"error", "err"}
type Converter func(addSource bool, replaceAttr func(groups []string, a slog.Attr) slog.Attr, loggerAttr []slog.Attr, groups []string, record *slog.Record) map[string]any
func DefaultConverter(addSource bool, replaceAttr func(groups []string, a slog.Attr) slog.Attr, loggerAttr []slog.Attr, groups []string, record *slog.Record) map[string]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
log := map[string]any{
"@timestamp": record.Time.UTC(),
"logger.name": name,
"logger.version": version,
"level": record.Level.String(),
"message": record.Message,
}
attrToDatadogLog("", attrs, &log)
return log
}
func attrToDatadogLog(base string, attrs []slog.Attr, log *map[string]any) {
for i := range attrs {
attr := attrs[i]
k := attr.Key
v := attr.Value
kind := attr.Value.Kind()
for _, errorKey := range ErrorKeys {
if attr.Key == errorKey && kind == slog.KindAny {
if err, ok := attr.Value.Any().(error); ok {
kind, message, stack := buildExceptions(err)
(*log)[base+k+".kind"] = kind
(*log)[base+k+".message"] = message
(*log)[base+k+".stack"] = stack
} else {
attrToDatadogLog(base+k+".", v.Group(), log)
}
}
}
if attr.Key == "user" && kind == slog.KindGroup {
attrToDatadogLog("usr.", v.Group(), log)
} else {
switch kind {
case slog.KindGroup:
attrToDatadogLog(base+k+".", v.Group(), log)
case slog.KindBool:
(*log)[base+k] = v.Bool()
case slog.KindFloat64:
(*log)[base+k] = v.Float64()
case slog.KindInt64:
(*log)[base+k] = v.Int64()
case slog.KindString:
(*log)[base+k] = v.String()
case slog.KindAny:
(*log)[base+k] = v.Any()
default:
(*log)[base+k] = slogcommon.ValueToString(v)
}
}
}
}
func buildExceptions(err error) (kind string, message string, stack string) {
return reflect.TypeOf(err).String(), err.Error(), ""
}