bbgo_origin/pkg/slack/slacklog/logrus_look.go

78 lines
1.5 KiB
Go
Raw Permalink Normal View History

2020-09-19 00:13:06 +00:00
package slacklog
import (
"context"
2020-08-07 01:15:50 +00:00
"fmt"
2020-09-05 08:22:46 +00:00
"strings"
"time"
2020-09-05 08:22:46 +00:00
"github.com/sirupsen/logrus"
"github.com/slack-go/slack"
"golang.org/x/time/rate"
)
var limiter = rate.NewLimiter(rate.Every(time.Minute), 45)
2020-08-11 00:37:27 +00:00
type LogHook struct {
Slack *slack.Client
ErrorChannel string
}
2020-09-19 01:05:06 +00:00
func NewLogHook(token string, channel string) *LogHook {
var client = slack.New(token)
return &LogHook{
2020-10-09 05:21:42 +00:00
Slack: client,
2020-09-19 01:05:06 +00:00
ErrorChannel: channel,
}
}
2020-08-11 00:37:27 +00:00
func (t *LogHook) Levels() []logrus.Level {
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 {
if !limiter.Allow() {
return nil
}
2020-10-09 07:59:33 +00:00
var 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"
}
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-08-07 01:15:50 +00:00
slackAttachments = append(slackAttachments, slack.Attachment{
2020-10-09 05:21:42 +00:00
Color: color,
Title: strings.ToUpper(e.Level.String()),
2020-08-07 01:15:50 +00:00
Fields: fields,
})
_, _, err := t.Slack.PostMessageContext(context.Background(), t.ErrorChannel,
2020-08-07 01:15:50 +00:00
slack.MsgOptionText(":balloon: "+e.Message, true),
slack.MsgOptionAttachments(slackAttachments...))
return err
}