-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
converter.go
55 lines (45 loc) · 1.56 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
package slogslack
import (
"log/slog"
slogcommon "github.com/samber/slog-common"
"github.com/slack-go/slack"
)
var SourceKey = "source"
type Converter func(addSource bool, replaceAttr func(groups []string, a slog.Attr) slog.Attr, loggerAttr []slog.Attr, groups []string, record *slog.Record) *slack.WebhookMessage
func DefaultConverter(addSource bool, replaceAttr func(groups []string, a slog.Attr) slog.Attr, loggerAttr []slog.Attr, groups []string, record *slog.Record) *slack.WebhookMessage {
// 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
message := &slack.WebhookMessage{}
message.Text = record.Message
message.Attachments = []slack.Attachment{
{
Color: ColorMapping[record.Level],
Fields: []slack.AttachmentField{},
},
}
attrToSlackMessage("", attrs, message)
return message
}
func attrToSlackMessage(base string, attrs []slog.Attr, message *slack.WebhookMessage) {
for i := range attrs {
attr := attrs[i]
k := attr.Key
v := attr.Value
kind := attr.Value.Kind()
if kind == slog.KindGroup {
attrToSlackMessage(base+k+".", v.Group(), message)
} else {
field := slack.AttachmentField{}
field.Title = base + k
field.Value = slogcommon.ValueToString(v)
message.Attachments[0].Fields = append(message.Attachments[0].Fields, field)
}
}
}