/
zap_hook.go
59 lines (52 loc) · 1.28 KB
/
zap_hook.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
package logging
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"time"
"github.com/bwmarrin/discordgo"
"go.uber.org/zap/zapcore"
)
// NewZapHookDiscord sends Zap log messages to a Discord Webhook
// TODO: ratelimit
func NewZapHookDiscord(serviceName, webhookURL string, client *http.Client) func(zapcore.Entry) error {
if webhookURL == "" || client == nil {
return func(_ zapcore.Entry) error {
return nil
}
}
return func(entry zapcore.Entry) error {
if entry.Level == zapcore.DebugLevel ||
entry.Level == zapcore.InfoLevel {
return nil
}
body, err := json.Marshal(discordgo.WebhookParams{
Username: strings.Title(serviceName),
Embeds: []*discordgo.MessageEmbed{
{
Title: "Logging message: " + strings.ToUpper(entry.Level.String()),
Description: entry.Message,
Timestamp: entry.Time.Format(time.RFC3339),
Color: 0, // TODO: color per log level
Footer: &discordgo.MessageEmbedFooter{
Text: "powered by Cacophony",
},
Fields: []*discordgo.MessageEmbedField{
{
Name: "caller",
Value: entry.Caller.String(),
},
},
},
},
})
if err != nil {
return err
}
_, err = client.Post(
webhookURL, "application/json", bytes.NewBuffer(body),
)
return err
}
}