|
9 | 9 | "net"
|
10 | 10 | "regexp"
|
11 | 11 | "runtime"
|
| 12 | + "sync" |
12 | 13 | "testing"
|
13 | 14 | "time"
|
14 | 15 | )
|
@@ -493,3 +494,44 @@ func TestCallerStackHandler(t *testing.T) {
|
493 | 494 | t.Fatalf("Wrong context value, got %s expected string matching %s", s, exp)
|
494 | 495 | }
|
495 | 496 | }
|
| 497 | + |
| 498 | +// tests that when logging concurrently to the same logger |
| 499 | +// from multiple goroutines that the calls are handled independently |
| 500 | +// this test tries to trigger a previous bug where concurrent calls could |
| 501 | +// corrupt each other's context values |
| 502 | +// |
| 503 | +// this test runs N concurrent goroutines each logging a fixed number of |
| 504 | +// records and a handler that buckets them based on the index passed in the context. |
| 505 | +// if the logger is not concurrent-safe then the values in the buckets will not all be the same |
| 506 | +// |
| 507 | +// https://github.com/inconshreveable/log15/pull/30 |
| 508 | +func TestConcurrent(t *testing.T) { |
| 509 | + root := New() |
| 510 | + // this was the first value that triggered |
| 511 | + // go to allocate extra capacity in the logger's context slice which |
| 512 | + // was necessary to trigger the bug |
| 513 | + const ctxLen = 34 |
| 514 | + l := root.New(make([]interface{}, ctxLen)...) |
| 515 | + const goroutines = 8 |
| 516 | + var res [goroutines]int |
| 517 | + l.SetHandler(SyncHandler(FuncHandler(func(r *Record) error { |
| 518 | + res[r.Ctx[ctxLen+1].(int)]++ |
| 519 | + return nil |
| 520 | + }))) |
| 521 | + var wg sync.WaitGroup |
| 522 | + wg.Add(goroutines) |
| 523 | + for i := 0; i < goroutines; i++ { |
| 524 | + go func(idx int) { |
| 525 | + defer wg.Done() |
| 526 | + for j := 0; j < 10000; j++ { |
| 527 | + l.Info("test message", "goroutine_idx", idx) |
| 528 | + } |
| 529 | + }(i) |
| 530 | + } |
| 531 | + wg.Wait() |
| 532 | + for _, val := range res[:] { |
| 533 | + if val != 10000 { |
| 534 | + t.Fatalf("Wrong number of messages for context: %+v", res) |
| 535 | + } |
| 536 | + } |
| 537 | +} |
0 commit comments