forked from johntdyer/slackrus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slackrus.go
94 lines (78 loc) · 1.94 KB
/
slackrus.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
// Package slackrus provides a Hipchat hook for the logrus loggin package.
package slackrus
import (
"fmt"
"github.com/Sirupsen/logrus"
"github.com/johntdyer/slack-go"
)
// Project version
const (
VERISON = "0.0.2"
)
// SlackrusHook is a logrus Hook for dispatching messages to the specified
// channel on Slack.
type SlackrusHook struct {
// Messages with a log level not contained in this array
// will not be dispatched. If nil, all messages will be dispatched.
AcceptedLevels []logrus.Level
HookURL string
IconURL string
Channel string
IconEmoji string
Username string
Asynchronous bool
}
// Levels sets which levels to sent to slack
func (sh *SlackrusHook) Levels() []logrus.Level {
if sh.AcceptedLevels == nil {
return AllLevels
}
return sh.AcceptedLevels
}
// Fire - Sent event to slack
func (sh *SlackrusHook) Fire(e *logrus.Entry) error {
color := ""
switch e.Level {
case logrus.DebugLevel:
color = "#9B30FF"
case logrus.InfoLevel:
color = "good"
case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
color = "danger"
default:
color = "warning"
}
msg := &slack.Message{
Username: sh.Username,
Channel: sh.Channel,
IconEmoji: sh.IconEmoji,
IconUrl: sh.IconURL,
}
attach := msg.NewAttachment()
// If there are fields we need to render them at attachments
if len(e.Data) > 0 {
// Add a header above field data
attach.Text = "Message fields"
for k, v := range e.Data {
slackField := &slack.Field{}
slackField.Title = k
slackField.Value = fmt.Sprint(v)
// If the field is <= 20 then we'll set it to short
if len(slackField.Value) <= 20 {
slackField.Short = true
}
attach.AddField(slackField)
}
attach.Pretext = e.Message
} else {
attach.Text = e.Message
}
attach.Fallback = e.Message
attach.Color = color
c := slack.NewClient(sh.HookURL)
if sh.Asynchronous {
go c.SendMessage(msg)
return nil
}
return c.SendMessage(msg)
}