notifier: redirect error, panic, fatal error to telegram

This commit is contained in:
c9s 2022-09-12 00:29:12 +08:00
parent cacc24fb3c
commit b8e18dd75c
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
4 changed files with 43 additions and 2 deletions

View File

@ -1012,6 +1012,8 @@ func (environ *Environment) setupTelegram(userConfig *Config, telegramBotToken s
var notifier = telegramnotifier.New(bot, opts...)
Notification.AddNotifier(notifier)
log.AddHook(telegramnotifier.NewLogHook(notifier))
// allocate a store, so that we can save the chatID for the owner
var messenger = interact.NewTelegram(bot)

View File

@ -0,0 +1,39 @@
package telegramnotifier
import (
"fmt"
"time"
"github.com/sirupsen/logrus"
"golang.org/x/time/rate"
)
var limiter = rate.NewLimiter(rate.Every(time.Minute), 3)
type LogHook struct {
notifier *Notifier
}
func NewLogHook(notifier *Notifier) *LogHook {
return &LogHook{
notifier: notifier,
}
}
func (t *LogHook) Levels() []logrus.Level {
return []logrus.Level{
logrus.ErrorLevel,
logrus.FatalLevel,
logrus.PanicLevel,
}
}
func (t *LogHook) Fire(e *logrus.Entry) error {
if !limiter.Allow() {
return nil
}
var message = fmt.Sprintf("[%s] %s", e.Level.String(), e.Message)
t.notifier.Notify(message)
return nil
}

View File

@ -35,7 +35,7 @@ func UseBroadcast() Option {
}
}
// New
// New returns a telegram notifier instance
func New(bot *telebot.Bot, options ...Option) *Notifier {
notifier := &Notifier{
bot: bot,

View File

@ -11,7 +11,7 @@ import (
"golang.org/x/time/rate"
)
var limiter = rate.NewLimiter(rate.Every(time.Minute), 45)
var limiter = rate.NewLimiter(rate.Every(time.Minute), 3)
type LogHook struct {
Slack *slack.Client