forked from samber/slog-graylog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
converter.go
106 lines (87 loc) · 1.94 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package sloggraylog
import (
"encoding"
"fmt"
"reflect"
"golang.org/x/exp/slog"
)
type Converter func(loggerAttr []slog.Attr, record *slog.Record) map[string]any
func DefaultConverter(loggerAttr []slog.Attr, record *slog.Record) map[string]any {
log := map[string]any{
"timestamp": record.Time.UTC(),
"level": record.Level.String(),
"message": record.Message,
}
extra := attrsToValue(loggerAttr)
record.Attrs(func(attr slog.Attr) bool {
for k, v := range attrsToValue([]slog.Attr{attr}) {
extra[k] = v
}
return true
})
if err, ok := extra["error"]; ok {
log["error"] = err
delete(extra, "error")
}
log["extra"] = extra
return log
}
func attrsToValue(attrs []slog.Attr) map[string]any {
log := map[string]any{}
for i := range attrs {
k, v := attrToValue(attrs[i])
log[k] = v
}
return log
}
func attrToValue(attr slog.Attr) (string, any) {
k := attr.Key
v := attr.Value
kind := v.Kind()
switch kind {
case slog.KindAny:
if k == "error" {
if err, ok := v.Any().(error); ok {
return k, buildExceptions(err)
}
}
return k, v.Any()
case slog.KindLogValuer:
return k, v.Any()
case slog.KindGroup:
return k, attrsToValue(v.Group())
case slog.KindInt64:
return k, v.Int64()
case slog.KindUint64:
return k, v.Uint64()
case slog.KindFloat64:
return k, v.Float64()
case slog.KindString:
return k, v.String()
case slog.KindBool:
return k, v.Bool()
case slog.KindDuration:
return k, v.Duration()
case slog.KindTime:
return k, v.Time().UTC()
default:
return k, anyValueToString(v)
}
}
func anyValueToString(v slog.Value) string {
if tm, ok := v.Any().(encoding.TextMarshaler); ok {
data, err := tm.MarshalText()
if err != nil {
return ""
}
return string(data)
}
return fmt.Sprintf("%+v", v.Any())
}
func buildExceptions(err error) map[string]any {
return map[string]any{
"kind": reflect.TypeOf(err).String(),
"error": err.Error(),
"stack": nil, // @TODO
}
}