-
Notifications
You must be signed in to change notification settings - Fork 4
/
logrusloki.go
154 lines (120 loc) · 3.54 KB
/
logrusloki.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package lokirus
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/sirupsen/logrus"
"github.com/yukitsune/lokirus/loki"
)
const pushLogsPath = "/loki/api/v1/push"
const levelKey = "level"
// LokiHook sends logs to Loki via HTTP.
type LokiHook struct {
host string
levels []logrus.Level
opts LokiHookOptions
}
// NewLokiHook creates a Loki hook for logrus
// if no levels are provided, then logrus.AllLevels is used
func NewLokiHook(host string, levels ...logrus.Level) *LokiHook {
return NewLokiHookWithOpts(host, NewLokiHookOptions(), levels...)
}
// NewLokiHookWithOpts creates a Loki hook for logrus with the specified LokiHookOptions
// if no levels are provided, then logrus.AllLevels is used
func NewLokiHookWithOpts(host string, opts LokiHookOptions, levels ...logrus.Level) *LokiHook {
if len(levels) == 0 {
levels = logrus.AllLevels
}
return &LokiHook{
host: host,
levels: levels,
opts: opts,
}
}
// Fire sends a log entry to Loki
func (hook *LokiHook) Fire(entry *logrus.Entry) error {
messageData, err := hook.formatMessage(entry)
if err != nil {
return fmt.Errorf("error formatting message: %s", err.Error())
}
stream := loki.NewStream()
stream.AddEntry(entry.Time, string(messageData))
hook.applyDynamicLabels(entry, stream)
hook.applyStaticLabels(stream)
hook.applyLevelLabel(entry, stream)
batch := loki.NewBatch()
batch.AddStream(stream)
req, err := hook.buildRequest(batch)
if err != nil {
return fmt.Errorf("error building request: %s", err.Error())
}
err = hook.sendRequest(req)
return err
}
// Levels returns the levels for which Fire will be called
func (hook *LokiHook) Levels() []logrus.Level {
return hook.levels
}
func (hook *LokiHook) formatMessage(entry *logrus.Entry) ([]byte, error) {
formatter := hook.opts.Formatter()
return formatter.Format(entry)
}
func (hook *LokiHook) applyDynamicLabels(entry *logrus.Entry, stream *loki.Stream) {
fn := hook.opts.DynamicLabelProvider()
dynamicLabels := fn(entry)
for k, v := range dynamicLabels {
stream.AddLabel(k, v)
}
}
func (hook *LokiHook) applyStaticLabels(stream *loki.Stream) {
for k, v := range hook.opts.StaticLabels() {
stream.AddLabel(k, v)
}
}
func (hook *LokiHook) applyLevelLabel(entry *logrus.Entry, stream *loki.Stream) {
level := hook.getLevel(entry.Level)
stream.AddLabel(levelKey, level)
}
func (hook *LokiHook) getLevel(level logrus.Level) string {
altValue, hasAltValue := hook.opts.LevelMap()[level]
if hasAltValue {
return altValue
}
return level.String()
}
func (hook *LokiHook) buildRequest(batch *loki.Batch) (*http.Request, error) {
endpoint := fmt.Sprintf("%s%s", hook.host, pushLogsPath)
data, err := json.Marshal(batch)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", endpoint, bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
if hook.opts.BasicAuth() != nil {
req.SetBasicAuth(hook.opts.BasicAuth().Username, hook.opts.BasicAuth().Password)
}
return req, nil
}
func (hook *LokiHook) sendRequest(req *http.Request) error {
resp, err := hook.opts.HttpClient().Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if !isSuccessStatusCode(resp.StatusCode) {
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error reading response (%s): %s", resp.Status, err.Error())
}
return fmt.Errorf("error posting loki batch (%s): %s", resp.Status, string(data))
}
return nil
}
func isSuccessStatusCode(code int) bool {
return code >= 200 && code <= 299
}