forked from saromanov/logrus-loki-hook
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlogrus_loki.go
88 lines (76 loc) · 1.91 KB
/
logrus_loki.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package hook
import (
"fmt"
"time"
"github.com/afiskon/promtail-client/promtail"
"github.com/sirupsen/logrus"
)
var supportedLevels = []logrus.Level{logrus.TraceLevel, logrus.DebugLevel, logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel}
// Config defines configuration for hook for Loki
type Config struct {
URL string
Labels string
BatchWait time.Duration
BatchEntriesNumber int
}
func (c *Config) setDefault() {
if c.URL == "" {
c.URL = "http://localhost:3100/api/prom/push"
}
if c.Labels == "" {
c.Labels = "{source=\"" + "test" + "\",job=\"" + "job" + "\"}"
}
if c.BatchWait == time.Second {
c.BatchWait = 5 * time.Second
}
if c.BatchEntriesNumber == 0 {
c.BatchEntriesNumber = 10000
}
}
type Hook struct {
client promtail.Client
}
// NewHook creates a new hook for Loki
func NewHook(c *Config) (*Hook, error) {
if c == nil {
c = &Config{}
}
c.setDefault()
conf := promtail.ClientConfig{
PushURL: c.URL,
Labels: c.Labels,
BatchWait: c.BatchWait,
BatchEntriesNumber: c.BatchEntriesNumber,
SendLevel: promtail.DEBUG,
PrintLevel: promtail.DISABLE,
}
loki, err := promtail.NewClientJson(conf)
if err != nil {
return nil, fmt.Errorf("unable to init promtail client: %v", err)
}
return &Hook{
client: loki,
}, nil
}
// Fire implements interface for logrus
func (hook *Hook) Fire(entry *logrus.Entry) error {
switch entry.Level {
case logrus.DebugLevel:
hook.client.Debugf(entry.Message)
case logrus.InfoLevel:
hook.client.Infof(entry.Message)
case logrus.WarnLevel:
hook.client.Warnf(entry.Message)
case logrus.ErrorLevel:
hook.client.Errorf(entry.Message)
case logrus.TraceLevel:
hook.client.Debugf(entry.Message)
default:
return fmt.Errorf("unknown log level")
}
return nil
}
// Levels retruns supported levels
func (hook *Hook) Levels() []logrus.Level {
return supportedLevels
}