-
Notifications
You must be signed in to change notification settings - Fork 4
/
logrusloki_test.go
369 lines (283 loc) · 8.24 KB
/
logrusloki_test.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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package lokirus_test
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"testing"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/yukitsune/lokirus"
"github.com/yukitsune/lokirus/loki"
)
const testFormatterPrefix = "this is a test"
type testFormatter struct {
}
func (f *testFormatter) Format(entry *logrus.Entry) ([]byte, error) {
return []byte(fmt.Sprintf("%s: %s", testFormatterPrefix, entry.Message)), nil
}
type mockRoundTripper struct {
req *http.Request
}
func (r *mockRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
r.req = req
return &http.Response{
StatusCode: http.StatusCreated,
Body: bodyReadCloser{bytes.NewBuffer([]byte{})},
}, nil
}
func (r *mockRoundTripper) UnmarshalRequest(v interface{}) error {
reqData, err := ioutil.ReadAll(r.req.Body)
if err != nil {
return err
}
err = json.Unmarshal(reqData, &v)
if err != nil {
return err
}
return nil
}
func (r *mockRoundTripper) Request() *http.Request {
return r.req
}
func (r *mockRoundTripper) BasicAuth() (string, string, bool) {
return r.req.BasicAuth()
}
type bodyReadCloser struct {
io.Reader
}
func (rc bodyReadCloser) Close() error {
return nil
}
func TestLokiHook_Fires(t *testing.T) {
// Arrange
client, roundTripper := getClient()
hook := lokirus.NewLokiHookWithOpts(
"",
lokirus.NewLokiHookOptions().
WithStaticLabels(lokirus.Labels{"test": t.Name()}).
WithHttpClient(client))
logger := logrus.New()
logger.AddHook(hook)
// Act
logger.Info(t.Name())
var sentBatch loki.Batch
err := roundTripper.UnmarshalRequest(&sentBatch)
assert.NoError(t, err)
// Assert
// Ensure the label and message were sent
assert.Equal(t, sentBatch.Streams[0].Labels["test"], t.Name())
assert.Contains(t, sentBatch.Streams[0].Entries[0][1], t.Name())
}
// This test checks that basic auth credentials gets sent
// if we configure the hook to do so.
func TestLokiHook_SendsBasicAuthCredentials(t *testing.T) {
client, roundTripper := getClient()
hook := lokirus.NewLokiHookWithOpts("",
lokirus.NewLokiHookOptions().
WithStaticLabels(lokirus.Labels{"test": t.Name()}).
WithBasicAuth("test-username", "test-password").
WithHttpClient(client))
logger := logrus.New()
logger.AddHook(hook)
logger.Info(t.Name())
username, password, ok := roundTripper.BasicAuth()
assert.True(t, ok)
assert.Equal(t, "test-username", username)
assert.Equal(t, "test-password", password)
}
// This tests checks that we are not sending basic auth credentials
// if we didn't configure them.
func TestLokiHook_NoUnnecessaryBasicAuth(t *testing.T) {
client, roundTripper := getClient()
hook := lokirus.NewLokiHookWithOpts("",
lokirus.NewLokiHookOptions().
WithStaticLabels(lokirus.Labels{"test": t.Name()}).
WithHttpClient(client))
logger := logrus.New()
logger.AddHook(hook)
logger.Info(t.Name())
username, password, ok := roundTripper.BasicAuth()
assert.False(t, ok)
assert.Empty(t, username)
assert.Empty(t, password)
}
func TestLokiHook_PushesToCorrectEndpoint(t *testing.T) {
// Arrange
client, roundTripper := getClient()
hook := lokirus.NewLokiHookWithOpts(
"http://loki:3100",
lokirus.NewLokiHookOptions().
WithHttpClient(client))
logger := logrus.New()
logger.AddHook(hook)
// Act
logger.Info(t.Name())
// Assert
// Ensure the request URI is correct
assert.Equal(t, "http://loki:3100/loki/api/v1/push", roundTripper.Request().URL.String())
}
func TestLokiHook_SendsStaticLabels(t *testing.T) {
// Arrange
staticLabels := lokirus.Labels{
"test": t.Name(),
"my_first_label": "abc",
"my_second_label": "123",
"my_third_label": "!@#",
}
client, roundTripper := getClient()
hook := lokirus.NewLokiHookWithOpts(
"",
lokirus.NewLokiHookOptions().
WithStaticLabels(staticLabels).
WithHttpClient(client))
logger := logrus.New()
logger.AddHook(hook)
// Ensure we get the same labels every time
for i := 0; i < 10; i++ {
// Act
logger.Infof("test %d", i)
var sentBatch loki.Batch
err := roundTripper.UnmarshalRequest(&sentBatch)
assert.NoError(t, err)
for k, v := range staticLabels {
sentValue, hasSentValue := sentBatch.Streams[0].Labels[k]
// Assert
// Ensure our static labels are all present
assert.True(t, hasSentValue)
assert.Equal(t, v, sentValue)
}
}
}
func TestLokiHook_SendsDynamicLabels(t *testing.T) {
// Arrange
// Every time we call the label provider, we'll return whatever counter is
// Counter will be incremented later
// It's a weird pattern, but it works
counter := 0
fn := func(entry *logrus.Entry) lokirus.Labels {
l := lokirus.Labels{
"count": strconv.Itoa(counter),
}
return l
}
client, roundTripper := getClient()
hook := lokirus.NewLokiHookWithOpts(
"",
lokirus.NewLokiHookOptions().
WithDynamicLabelProvider(fn).
WithHttpClient(client))
logger := logrus.New()
logger.AddHook(hook)
for counter = 0; counter < 10; counter++ {
// Act
logger.Infof(t.Name())
var sentBatch loki.Batch
err := roundTripper.UnmarshalRequest(&sentBatch)
assert.NoError(t, err)
sentValue, hasSentValue := sentBatch.Streams[0].Labels["count"]
// Assert
// Ensure the count label is different every time
assert.True(t, hasSentValue)
assert.Equal(t, strconv.Itoa(counter), sentValue)
}
}
func TestLokiHook_SendsLevelLabel(t *testing.T) {
// Arrange
// Intentionally ignoring Fatal and Panic as they will kill the program
// Debug and Trace aren't sent from hooks
levels := []logrus.Level{
logrus.ErrorLevel,
logrus.WarnLevel,
logrus.InfoLevel,
}
client, roundTripper := getClient()
hook := lokirus.NewLokiHookWithOpts(
"",
lokirus.NewLokiHookOptions().
WithHttpClient(client),
levels...)
logger := logrus.New()
logger.AddHook(hook)
for _, level := range levels {
levelStr := level.String()
// Act
logger.Log(level, t.Name())
var sentBatch loki.Batch
err := roundTripper.UnmarshalRequest(&sentBatch)
assert.NoError(t, err)
// Assert
// Ensure the level label is present and set to the correct value
assert.Equal(t, levelStr, sentBatch.Streams[0].Labels["level"])
}
}
func TestLokiHook_ReMapsLevels(t *testing.T) {
// Arrange
// Intentionally ignoring Fatal and Panic as they will kill the program
// Debug and Trace aren't sent from hooks
levelMap := lokirus.LevelMap{
logrus.ErrorLevel: "my_error",
logrus.WarnLevel: "your_warning",
// We'll let InfoLevel remain the same so we can test that unmapped levels use their default value
}
client, roundTripper := getClient()
hook := lokirus.NewLokiHookWithOpts(
"",
lokirus.NewLokiHookOptions().
WithLevelMap(levelMap).
WithHttpClient(client))
logger := logrus.New()
logger.AddHook(hook)
for logrusLevel, customLevel := range levelMap {
// Act
logger.Log(logrusLevel, t.Name())
var sentBatch loki.Batch
err := roundTripper.UnmarshalRequest(&sentBatch)
assert.NoError(t, err)
// Assert
// Ensure the level label is our custom label
assert.Equal(t, customLevel, sentBatch.Streams[0].Labels["level"])
}
// Test InfoLevel manually since it's not re-mapped
// Act
logger.Log(logrus.InfoLevel, t.Name())
var sentBatch loki.Batch
err := roundTripper.UnmarshalRequest(&sentBatch)
assert.NoError(t, err)
// Assert
// Ensure the level label still uses the default value with the other mappings present
assert.Equal(t, logrus.InfoLevel.String(), sentBatch.Streams[0].Labels["level"])
}
//// If any of these tests are passing, then this works...
//func TestLokiHook_UsesCustomHttpClient(t *testing.T) {
//
//}
func TestLokiHook_UsesCustomFormatter(t *testing.T) {
// Arrange
client, roundTripper := getClient()
hook := lokirus.NewLokiHookWithOpts(
"",
lokirus.NewLokiHookOptions().
WithFormatter(&testFormatter{}).
WithHttpClient(client))
logger := logrus.New()
logger.AddHook(hook)
// Act
logger.Infoln(t.Name())
var sentBatch loki.Batch
err := roundTripper.UnmarshalRequest(&sentBatch)
assert.NoError(t, err)
// Assert
// Ensure the sent log message used the formatter
sentMessage := sentBatch.Streams[0].Entries[0][1]
assert.Contains(t, sentMessage, testFormatterPrefix)
}
func getClient() (*http.Client, *mockRoundTripper) {
client := &http.Client{}
roundTripper := &mockRoundTripper{}
client.Transport = roundTripper
return client, roundTripper
}