forked from samber/slog-common
-
Notifications
You must be signed in to change notification settings - Fork 0
/
attributes.go
320 lines (270 loc) · 6.85 KB
/
attributes.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package slogcommon
import (
"encoding"
"fmt"
"log/slog"
"net/http"
"reflect"
"runtime"
"slices"
"strconv"
"strings"
"github.com/samber/lo"
)
type ReplaceAttrFn = func(groups []string, a slog.Attr) slog.Attr
func AppendRecordAttrsToAttrs(attrs []slog.Attr, groups []string, record *slog.Record) []slog.Attr {
output := slices.Clone(attrs)
slices.Reverse(groups)
record.Attrs(func(attr slog.Attr) bool {
for i := range groups {
attr = slog.Group(groups[i], attr)
}
output = append(output, attr)
return true
})
return output
}
func ReplaceAttrs(fn ReplaceAttrFn, groups []string, attrs ...slog.Attr) []slog.Attr {
for i := range attrs {
attr := attrs[i]
value := attr.Value.Resolve()
if value.Kind() == slog.KindGroup {
attrs[i].Value = slog.GroupValue(ReplaceAttrs(fn, append(groups, attr.Key), value.Group()...)...)
} else if fn != nil {
attrs[i] = fn(groups, attr)
}
}
return attrs
}
func AttrsToMap(attrs ...slog.Attr) map[string]any {
output := map[string]any{}
attrsByKey := groupValuesByKey(attrs)
for k, values := range attrsByKey {
v := mergeAttrValues(values...)
if v.Kind() == slog.KindGroup {
output[k] = AttrsToMap(v.Group()...)
} else {
output[k] = v.Any()
}
}
return output
}
func groupValuesByKey(attrs []slog.Attr) map[string][]slog.Value {
result := map[string][]slog.Value{}
for _, item := range attrs {
key := item.Key
result[key] = append(result[key], item.Value)
}
return result
}
func mergeAttrValues(values ...slog.Value) slog.Value {
v := values[0]
for i := 1; i < len(values); i++ {
if v.Kind() != slog.KindGroup || values[i].Kind() != slog.KindGroup {
v = values[i]
continue
}
v = slog.GroupValue(append(v.Group(), values[i].Group()...)...)
}
return v
}
func AttrToValue(attr slog.Attr) (string, any) {
k := attr.Key
v := attr.Value
kind := v.Kind()
switch kind {
case slog.KindAny:
return k, v.Any()
case slog.KindLogValuer:
return k, v.Any()
case slog.KindGroup:
return k, AttrsToMap(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 AttrsToString(attrs ...slog.Attr) map[string]string {
output := map[string]string{}
for i := range attrs {
attr := attrs[i]
k, v := attr.Key, attr.Value
output[k] = ValueToString(v)
}
return output
}
func ValueToString(v slog.Value) string {
switch v.Kind() {
case slog.KindAny:
return AnyValueToString(v)
case slog.KindLogValuer:
return AnyValueToString(v)
case slog.KindGroup:
return AnyValueToString(v)
case slog.KindInt64:
return fmt.Sprintf("%d", v.Int64())
case slog.KindUint64:
return fmt.Sprintf("%d", v.Uint64())
case slog.KindFloat64:
return fmt.Sprintf("%f", v.Float64())
case slog.KindString:
return v.String()
case slog.KindBool:
return strconv.FormatBool(v.Bool())
case slog.KindDuration:
return v.Duration().String()
case slog.KindTime:
return v.Time().UTC().String()
default:
return AnyValueToString(v)
}
}
func ReplaceError(attrs []slog.Attr, errorKeys ...string) []slog.Attr {
replaceAttr := func(groups []string, a slog.Attr) slog.Attr {
if len(groups) > 1 {
return a
}
for i := range errorKeys {
if a.Key == errorKeys[i] {
if err, ok := a.Value.Any().(error); ok {
return slog.Any(a.Key, FormatError(err))
}
}
}
return a
}
return ReplaceAttrs(replaceAttr, []string{}, attrs...)
}
func ExtractError(attrs []slog.Attr, errorKeys ...string) ([]slog.Attr, error) {
for i := range attrs {
attr := attrs[i]
if !slices.Contains(errorKeys, attr.Key) {
continue
}
if err, ok := attr.Value.Resolve().Any().(error); ok {
return append(attrs[:i], attrs[i+1:]...), err
}
}
return attrs, nil
}
func FormatErrorKey(values map[string]any, errorKeys ...string) map[string]any {
for _, errorKey := range errorKeys {
if err, ok := values[errorKey]; ok {
if e, ok := err.(error); ok {
values[errorKey] = FormatError(e)
break
}
}
}
return values
}
func FormatError(err error) map[string]any {
return map[string]any{
"kind": reflect.TypeOf(err).String(),
"error": err.Error(),
"stack": nil, // @TODO
}
}
func FormatRequest(req *http.Request, ignoreHeaders bool) map[string]any {
output := map[string]any{
"host": req.Host,
"method": req.Method,
"url": map[string]any{
"url": req.URL.String(),
"scheme": req.URL.Scheme,
"host": req.URL.Host,
"path": req.URL.Path,
"raw_query": req.URL.RawQuery,
"fragment": req.URL.Fragment,
"query": lo.MapEntries(req.URL.Query(), func(key string, values []string) (string, string) {
return key, strings.Join(values, ",")
}),
},
}
if !ignoreHeaders {
output["headers"] = lo.MapEntries(req.Header, func(key string, values []string) (string, string) {
return key, strings.Join(values, ",")
})
}
return output
}
func Source(sourceKey string, r *slog.Record) slog.Attr {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
var args []any
if f.Function != "" {
args = append(args, slog.String("function", f.Function))
}
if f.File != "" {
args = append(args, slog.String("file", f.File))
}
if f.Line != 0 {
args = append(args, slog.Int("line", f.Line))
}
return slog.Group(sourceKey, args...)
}
func StringSource(sourceKey string, r *slog.Record) slog.Attr {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
return slog.String(sourceKey, fmt.Sprintf("%s:%d (%s)", f.File, f.Line, f.Function))
}
func FindAttribute(attrs []slog.Attr, groups []string, key string) (slog.Attr, bool) {
// group traversal
if len(groups) > 0 {
for _, attr := range attrs {
if attr.Value.Kind() == slog.KindGroup && attr.Key == groups[0] {
attr, found := FindAttribute(attr.Value.Group(), groups[1:], key)
if found {
return attr, true
}
}
}
return slog.Attr{}, false
}
// starting here, groups is empty
for _, attr := range attrs {
if attr.Key == key {
return attr, true
}
}
return slog.Attr{}, false
}
func RemoveEmptyAttrs(attrs []slog.Attr) []slog.Attr {
return lo.FilterMap(attrs, func(attr slog.Attr, _ int) (slog.Attr, bool) {
if attr.Key == "" {
return attr, false
}
if attr.Value.Kind() == slog.KindGroup {
values := RemoveEmptyAttrs(attr.Value.Group())
if len(values) == 0 {
return attr, false
}
attr.Value = slog.GroupValue(values...)
return attr, true
}
return attr, !attr.Value.Equal(slog.Value{})
})
}