forked from johntdyer/slackrus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzuliprus.go
108 lines (94 loc) · 2.38 KB
/
zuliprus.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
// Package zuliprus provides a Slack hook for the logrus loggin package.
package zuliprus
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"github.com/ifo/gozulipbot"
"github.com/sirupsen/logrus"
)
// Project version
const (
VERISON = "0.0.3"
)
// ZuliprusHook is a logrus Hook for dispatching messages to the specified
// channel on Slack.
type ZuliprusHook 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
APIURL string
APIKey string
Email string
Stream string
UserEmails []string
Topic string
Asynchronous bool
Disabled bool
FormatFn FmtFunction
}
type FmtFunction func(e *logrus.Entry) string
var MsgFmtFn = func(e *logrus.Entry) string {
return fmt.Sprintf("%s> *%s* : %s", LevelPrefixFn(e), e.Time.Format("2006-01-02T15:04:05"), e.Message)
}
// Levels sets which levels to sent to slack
func (sh *ZuliprusHook) Levels() []logrus.Level {
if sh.AcceptedLevels == nil {
return AllLevels
}
return sh.AcceptedLevels
}
// Fire - Send event to zulip
func (sh *ZuliprusHook) Fire(e *logrus.Entry) error {
if sh.Disabled {
return nil
}
msg := gozulipbot.Message{
Stream: sh.Stream,
Topic: sh.Topic,
Emails: sh.UserEmails,
Content: MsgFmtFn(e),
}
// If there are fields they will not be send, special handling?
if sh.Asynchronous {
go sh.sendMessage(msg)
return nil
}
return sh.sendMessage(msg)
}
type LevelPrefix func(e *logrus.Entry) string
var LevelPrefixFn = func(e *logrus.Entry) string {
color := ""
switch e.Level {
case logrus.DebugLevel:
color = "```c++\nDEBUG\n```\n"
case logrus.InfoLevel:
color = "```bash\nINFO\n```\n"
case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
color = "```terraform\nERROR\n```\n"
default:
color = "```apacheconf\nWARN\n```\n"
}
return color
}
func (sh *ZuliprusHook) newClient() *gozulipbot.Bot {
return &gozulipbot.Bot{
APIKey: sh.APIKey,
APIURL: sh.APIURL,
Email: sh.Email,
Client: &http.Client{},
}
}
func (sh *ZuliprusHook) sendMessage(message gozulipbot.Message) error {
bot := sh.newClient()
resp, err := bot.Message(message)
if err != nil {
return err
}
if resp.StatusCode != 200 {
t, _ := ioutil.ReadAll(resp.Body)
return errors.New(fmt.Sprintf("ZulipError: %d %s", resp.StatusCode, t))
}
return nil
}