2020-07-13 04:34:15 +00:00
|
|
|
package slack
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-08-07 01:15:50 +00:00
|
|
|
"fmt"
|
2020-07-13 04:34:15 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
"github.com/slack-go/slack"
|
2020-08-07 01:15:50 +00:00
|
|
|
"strings"
|
2020-07-13 04:34:15 +00:00
|
|
|
)
|
|
|
|
|
2020-08-11 00:37:27 +00:00
|
|
|
type LogHook struct {
|
2020-07-13 04:34:15 +00:00
|
|
|
Slack *slack.Client
|
|
|
|
ErrorChannel string
|
|
|
|
}
|
|
|
|
|
2020-08-11 00:37:27 +00:00
|
|
|
func (t *LogHook) Levels() []logrus.Level {
|
2020-07-13 04:34:15 +00:00
|
|
|
return []logrus.Level{
|
|
|
|
// log.InfoLevel,
|
|
|
|
logrus.ErrorLevel,
|
|
|
|
logrus.PanicLevel,
|
|
|
|
// log.WarnLevel,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-11 00:37:27 +00:00
|
|
|
func (t *LogHook) Fire(e *logrus.Entry) error {
|
2020-07-13 04:34:15 +00:00
|
|
|
var color = "#F0F0F0"
|
|
|
|
|
|
|
|
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"
|
|
|
|
}
|
|
|
|
|
|
|
|
var slackAttachments []slack.Attachment = nil
|
|
|
|
|
2020-08-07 01:15:50 +00:00
|
|
|
// error fields
|
|
|
|
var fields []slack.AttachmentField
|
|
|
|
for k, d := range e.Data {
|
|
|
|
fields = append(fields, slack.AttachmentField{
|
|
|
|
Title: k, Value: fmt.Sprintf("%v", d),
|
2020-07-13 04:34:15 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-08-07 01:15:50 +00:00
|
|
|
slackAttachments = append(slackAttachments, slack.Attachment{
|
|
|
|
Color: color,
|
|
|
|
Title: strings.ToUpper(e.Level.String()),
|
|
|
|
Fields: fields,
|
|
|
|
})
|
|
|
|
|
2020-07-13 04:34:15 +00:00
|
|
|
_, _, err := t.Slack.PostMessageContext(context.Background(), t.ErrorChannel,
|
2020-08-07 01:15:50 +00:00
|
|
|
slack.MsgOptionText(":balloon: "+e.Message, true),
|
2020-07-13 04:34:15 +00:00
|
|
|
slack.MsgOptionAttachments(slackAttachments...))
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|