-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
converter.go
51 lines (39 loc) · 1.34 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
package slogquickwit
import (
"log/slog"
slogcommon "github.com/samber/slog-common"
)
var SourceKey = "source"
var ContextKey = "context"
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
attrs = slogcommon.ReplaceAttrs(replaceAttr, []string{}, attrs...)
attrs = slogcommon.RemoveEmptyAttrs(attrs)
// handler formatter
log := map[string]any{
"logger.name": name,
"logger.version": version,
"timestamp": record.Time.UTC(),
"level": record.Level.String(),
"message": record.Message,
}
if addSource {
attrs = append(attrs, slogcommon.Source(SourceKey, record))
}
context := slogcommon.AttrsToMap(attrs...)
for _, errorKey := range ErrorKeys {
if err, ok := context[errorKey]; ok {
if e, ok := err.(error); ok {
log[errorKey] = slogcommon.FormatError(e)
delete(context, errorKey)
break
}
}
}
log[ContextKey] = context
return log
}