| 1 | // Copyright (c) 2012-2016 Eli Janssen |
| 2 | // Use of this source code is governed by an MIT-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | // |
| 5 | // some parts from: https://brandur.org/t-parallel |
| 6 | |
| 7 | package mlog |
| 8 | |
| 9 | import ( |
| 10 | "fmt" |
| 11 | "testing" |
| 12 | ) |
| 13 | |
| 14 | // TestoingLogWriter is an adapter between mlog and Go's testing package, |
| 15 | // which lets us send all output to `t.Log` so that it's correctly |
| 16 | // collated with the test that emitted it. This helps especially when |
| 17 | // using parallel testing where output would otherwise be interleaved |
| 18 | // and make debugging extremely difficult. |
| 19 | type TestingLogWriter struct { |
| 20 | tb testing.TB |
| 21 | } |
| 22 | |
| 23 | func (lw *TestingLogWriter) Write(p []byte) (n int, err error) { |
| 24 | // Unfortunately, even with this call to `t.Helper()` there's no |
| 25 | // way to correctly attribute the log location to where it's |
| 26 | // actually emitted in our code (everything shows up under |
| 27 | // `logger.go`). A good explanation of this problem and possible |
| 28 | // future solutions here: |
| 29 | // |
| 30 | // https://github.com/neilotoole/slogt#deficiency |
| 31 | if lw == nil { |
| 32 | return 0, nil |
| 33 | } |
| 34 | if lw.tb == nil { |
| 35 | fmt.Println("got nil testing.TB") |
| 36 | return 0, fmt.Errorf("got a nil testing.TBf") |
| 37 | } |
| 38 | lw.tb.Helper() |
| 39 | lw.tb.Logf(string(p)) |
| 40 | return len(p), nil |
| 41 | } |