forked from inconshreveable/log15
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog15_test.go
489 lines (398 loc) · 10.3 KB
/
log15_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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
package log15
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"net"
"sync"
"testing"
"time"
)
func testHandler() (Handler, func() Record) {
var rec *Record
return FuncHandler(func(r Record) error {
rec = &r
return nil
}),
func() Record {
if rec != nil {
return *rec
} else {
return Record{}
}
}
}
func testLogger() (Logger, Handler, func() Record) {
l := New()
h, r := testHandler()
l.SetHandler(LazyHandler(h))
return l, h, r
}
func TestLazy(t *testing.T) {
t.Parallel()
x := 1
lazy := func() int {
return x
}
l, _, r := testLogger()
l.Info("", "x", Lazy{lazy})
if r().Ctx[1] != 1 {
t.Fatalf("Lazy function not evaluated, got %v, expected %d", r().Ctx[1], 1)
}
x = 2
l.Info("", "x", Lazy{lazy})
if r().Ctx[1] != 2 {
t.Fatalf("Lazy function not evaluated, got %v, expected %d", r().Ctx[1], 1)
}
}
func TestInvalidLazy(t *testing.T) {
t.Parallel()
l, _, r := testLogger()
validate := func() {
if len(r().Ctx) < 4 {
t.Fatalf("Invalid lazy, got %d args, expecting at least 4", len(r().Ctx))
}
if r().Ctx[2] != errorKey {
t.Fatalf("Invalid lazy, got key %s expecting %s", r().Ctx[2], errorKey)
}
}
l.Info("", "x", Lazy{1})
validate()
l.Info("", "x", Lazy{func(x int) int { return x }})
validate()
l.Info("", "x", Lazy{func() {}})
validate()
}
func TestCtx(t *testing.T) {
t.Parallel()
l, _, r := testLogger()
l.Info("", Ctx{"x": 1, "y": "foo", "tester": t})
if len(r().Ctx) != 6 {
t.Fatalf("Expecting Ctx tansformed into %d ctx args, got %d: %v", 6, len(r().Ctx), r().Ctx)
}
}
func testFormatter(f Format) (Logger, *bytes.Buffer) {
l := New()
var buf bytes.Buffer
l.SetHandler(StreamHandler(&buf, f))
return l, &buf
}
func TestJson(t *testing.T) {
t.Parallel()
l, buf := testFormatter(JsonFormat())
l.Error("some message", "x", 1, "y", 3.2)
var v map[string]interface{}
decoder := json.NewDecoder(buf)
if err := decoder.Decode(&v); err != nil {
t.Fatalf("Error decoding JSON: %v", v)
}
validate := func(key string, expected interface{}) {
if v[key] != expected {
t.Fatalf("Got %v expected %v for %v", v[key], expected, key)
}
}
validate("msg", "some message")
validate("x", float64(1)) // all numbers are floats in JSON land
validate("y", 3.2)
validate("lvl", "eror")
}
func TestJSONMap(t *testing.T) {
m := map[string]interface{}{
"name": "gopher",
"age": float64(5),
"language": "go",
}
l, buf := testFormatter(JsonFormat())
l.Error("logging structs", "struct", m)
var v map[string]interface{}
decoder := json.NewDecoder(buf)
if err := decoder.Decode(&v); err != nil {
t.Fatalf("Error decoding JSON: %v", v)
}
checkMap := func(key string, expected interface{}) {
if m[key] != expected {
t.Fatalf("Got %v expected %v for %v", m[key], expected, key)
}
}
mv := v["struct"].(map[string]interface{})
checkMap("name", mv["name"])
checkMap("age", mv["age"])
checkMap("language", mv["language"])
}
type testtype struct {
name string
}
func (tt testtype) String() string {
return tt.name
}
func TestLogfmt(t *testing.T) {
t.Parallel()
var nilVal *testtype
l, buf := testFormatter(LogfmtFormat())
l.Error("some message", "x", 1, "y", 3.2, "equals", "=", "quote", "\"",
"nil", nilVal, "carriage_return", "bang"+string('\r')+"foo", "tab", "bar baz", "newline", "foo\nbar")
// skip timestamp in comparison
got := buf.Bytes()[27:buf.Len()]
expected := []byte(`lvl=eror msg="some message" x=1 y=3.200 equals="=" quote="\"" nil=nil carriage_return="bang\rfoo" tab="bar\tbaz" newline="foo\nbar"` + "\n")
if !bytes.Equal(got, expected) {
t.Fatalf("Got %s, expected %s", got, expected)
}
}
func TestMultiHandler(t *testing.T) {
t.Parallel()
h1, r1 := testHandler()
h2, r2 := testHandler()
l := New()
l.SetHandler(MultiHandler(h1, h2))
l.Debug("clone")
if r1().Msg != "clone" {
t.Fatalf("wrong value for h1.Msg. Got %s expected %s", r1().Msg, "clone")
}
if r2().Msg != "clone" {
t.Fatalf("wrong value for h2.Msg. Got %s expected %s", r2().Msg, "clone")
}
}
type waitHandler struct {
ch chan Record
}
func (h *waitHandler) Log(r Record) error {
h.ch <- r
return nil
}
func TestBufferedHandler(t *testing.T) {
t.Parallel()
ch := make(chan Record)
l := New()
l.SetHandler(BufferedHandler(0, &waitHandler{ch}))
l.Debug("buffer")
if r := <-ch; r.Msg != "buffer" {
t.Fatalf("wrong value for r.Msg. Got %s expected %s", r.Msg, "")
}
}
func TestLogContext(t *testing.T) {
t.Parallel()
l, _, r := testLogger()
l = l.New("foo", "bar")
l.Crit("baz")
if len(r().Ctx) != 2 {
t.Fatalf("Expected logger context in record context. Got length %d, expected %d", len(r().Ctx), 2)
}
if r().Ctx[0] != "foo" {
t.Fatalf("Wrong context key, got %s expected %s", r().Ctx[0], "foo")
}
if r().Ctx[1] != "bar" {
t.Fatalf("Wrong context value, got %s expected %s", r().Ctx[1], "bar")
}
}
func TestMapCtx(t *testing.T) {
t.Parallel()
l, _, r := testLogger()
l.Crit("test", Ctx{"foo": "bar"})
if len(r().Ctx) != 2 {
t.Fatalf("Wrong context length, got %d, expected %d", len(r().Ctx), 2)
}
if r().Ctx[0] != "foo" {
t.Fatalf("Wrong context key, got %s expected %s", r().Ctx[0], "foo")
}
if r().Ctx[1] != "bar" {
t.Fatalf("Wrong context value, got %s expected %s", r().Ctx[1], "bar")
}
}
func TestLvlFilterHandler(t *testing.T) {
t.Parallel()
l := New()
h, r := testHandler()
l.SetHandler(LvlFilterHandler(LvlWarn, h))
l.Info("info'd")
if r().Msg != "" {
t.Fatalf("Expected zero record, but got record with msg: %v", r().Msg)
}
l.Warn("warned")
if r().Msg != "warned" {
t.Fatalf("Got record msg %s expected %s", r().Msg, "warned")
}
l.Warn("error'd")
if r().Msg != "error'd" {
t.Fatalf("Got record msg %s expected %s", r().Msg, "error'd")
}
}
func TestNetHandler(t *testing.T) {
t.Parallel()
l, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Failed to listen: %v", l)
}
errs := make(chan error)
go func() {
c, err := l.Accept()
if err != nil {
errs <- fmt.Errorf("Failed to accept connection: %v", err)
return
}
rd := bufio.NewReader(c)
s, err := rd.ReadString('\n')
if err != nil {
errs <- fmt.Errorf("Failed to read string: %v", err)
return
}
got := s[27:]
expected := "lvl=info msg=test x=1\n"
if got != expected {
t.Errorf("Got log line %s, expected %s", got, expected)
}
errs <- nil
}()
lg := New()
h, err := NetHandler("tcp", l.Addr().String(), LogfmtFormat())
if err != nil {
t.Fatal(err)
}
lg.SetHandler(h)
lg.Info("test", "x", 1)
select {
case <-time.After(time.Second):
t.Fatalf("Test timed out!")
case err := <-errs:
if err != nil {
t.Fatal(err)
}
}
}
func TestMatchFilterHandler(t *testing.T) {
t.Parallel()
l, h, r := testLogger()
l.SetHandler(MatchFilterHandler("err", nil, h))
l.Crit("test", "foo", "bar")
if r().Msg != "" {
t.Fatalf("expected filter handler to discard msg")
}
l.Crit("test2", "err", "bad fd")
if r().Msg != "" {
t.Fatalf("expected filter handler to discard msg")
}
l.Crit("test3", "err", nil)
if r().Msg != "test3" {
t.Fatalf("expected filter handler to allow msg")
}
}
func TestMatchFilterBuiltin(t *testing.T) {
t.Parallel()
l, h, r := testLogger()
l.SetHandler(MatchFilterHandler("lvl", LvlError, h))
l.Info("does not pass")
if r().Msg != "" {
t.Fatalf("got info level record that should not have matched")
}
l.Error("error!")
if r().Msg != "error!" {
t.Fatalf("did not get error level record that should have matched")
}
l.SetHandler(MatchFilterHandler("msg", "matching message", h))
l.Info("doesn't match")
if r().Msg != "error!" {
t.Fatalf("got record with wrong message matched")
}
l.Debug("matching message")
if r().Msg != "matching message" {
t.Fatalf("did not get record which matches")
}
}
type failingWriter struct {
fail bool
}
func (w *failingWriter) Write(buf []byte) (int, error) {
if w.fail {
return 0, errors.New("fail")
}
return len(buf), nil
}
func TestFailoverHandler(t *testing.T) {
t.Parallel()
l := New()
h, r := testHandler()
w := &failingWriter{false}
l.SetHandler(FailoverHandler(
StreamHandler(w, JsonFormat()),
h))
l.Debug("test ok")
if r().Msg != "" {
t.Fatalf("expected no failover")
}
w.fail = true
l.Debug("test failover", "x", 1)
if r().Msg != "test failover" {
t.Fatalf("expected failover")
}
if len(r().Ctx) != 4 {
t.Fatalf("expected additional failover ctx")
}
got := r().Ctx[2]
expected := "failover_err_0"
if got != expected {
t.Fatalf("expected failover ctx. got: %s, expected %s", got, expected)
}
}
// https://github.com/inconshreveable/log15/issues/16
func TestIndependentSetHandler(t *testing.T) {
t.Parallel()
parent, _, r := testLogger()
child := parent.New()
child.SetHandler(DiscardHandler())
parent.Info("test")
if r().Msg != "test" {
t.Fatalf("parent handler affected by child")
}
}
// https://github.com/inconshreveable/log15/issues/16
func TestInheritHandler(t *testing.T) {
t.Parallel()
parent, _, r := testLogger()
child := parent.New()
parent.SetHandler(DiscardHandler())
child.Info("test")
if r().Msg == "test" {
t.Fatalf("child handler affected not affected by parent")
}
}
// tests that when logging concurrently to the same logger
// from multiple goroutines that the calls are handled independently
// this test tries to trigger a previous bug where concurrent calls could
// corrupt each other's context values
//
// this test runs N concurrent goroutines each logging a fixed number of
// records and a handler that buckets them based on the index passed in the context.
// if the logger is not concurrent-safe then the values in the buckets will not all be the same
//
// https://github.com/inconshreveable/log15/pull/30
func TestConcurrent(t *testing.T) {
root := New()
// this was the first value that triggered
// go to allocate extra capacity in the logger's context slice which
// was necessary to trigger the bug
const ctxLen = 34
l := root.New(make([]interface{}, ctxLen)...)
const goroutines = 8
var res [goroutines]int
l.SetHandler(SyncHandler(FuncHandler(func(r Record) error {
res[r.Ctx[ctxLen+1].(int)]++
return nil
})))
var wg sync.WaitGroup
wg.Add(goroutines)
for i := 0; i < goroutines; i++ {
go func(idx int) {
defer wg.Done()
for j := 0; j < 10000; j++ {
l.Info("test message", "goroutine_idx", idx)
}
}(i)
}
wg.Wait()
for _, val := range res[:] {
if val != 10000 {
t.Fatalf("Wrong number of messages for context: %+v", res)
}
}
}