-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger_hook.go
52 lines (44 loc) · 1.04 KB
/
logger_hook.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
package rice
import (
"bytes"
"context"
"time"
"github.com/nikoksr/notify"
"github.com/rs/zerolog"
)
type NotifyHook struct {
Notifier *notify.Notify
}
func NewNotifyHook() *NotifyHook {
return &NotifyHook{Notifier: notify.New()}
}
func (t *NotifyHook) AddTelegramBot(token, proxy string, chatID ...int64) *NotifyHook {
telegramService, err := NewTelegramService(token, proxy)
if err != nil {
return t
}
telegramService.AddReceivers(chatID...)
t.Notifier.UseServices(telegramService)
return t
}
func (t *NotifyHook) Run(e *zerolog.Event, level zerolog.Level, message string) {
if level > zerolog.DebugLevel {
go func() {
_ = t.send(level.String(), message)
}()
}
}
func (t *NotifyHook) Write(p []byte) (n int, err error) {
go func() {
_ = t.send("", "<pre><code>"+bytes.NewBuffer(p).String()+"</code></pre>")
}()
return len(p), nil
}
func (t *NotifyHook) send(title, msg string) error {
ctx, cancel := context.WithTimeout(
context.Background(),
30*time.Second,
)
defer cancel()
return t.Notifier.Send(ctx, title, msg)
}