Merge pull request #937 from c9s/feature/telegram-error-log-hook

notifier: redirect error, panic, fatal error to telegram
This commit is contained in:
Yo-An Lin 2022-09-12 00:39:12 +08:00 committed by GitHub
commit 4ea723d1d8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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...) var notifier = telegramnotifier.New(bot, opts...)
Notification.AddNotifier(notifier) Notification.AddNotifier(notifier)
log.AddHook(telegramnotifier.NewLogHook(notifier))
// allocate a store, so that we can save the chatID for the owner // allocate a store, so that we can save the chatID for the owner
var messenger = interact.NewTelegram(bot) 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 { func New(bot *telebot.Bot, options ...Option) *Notifier {
notifier := &Notifier{ notifier := &Notifier{
bot: bot, bot: bot,

View File

@ -11,7 +11,7 @@ import (
"golang.org/x/time/rate" "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 { type LogHook struct {
Slack *slack.Client Slack *slack.Client