Skip to content

Commit

Permalink
add testing logger helper
Browse files Browse the repository at this point in the history
  • Loading branch information
dropwhile committed Aug 27, 2023
1 parent 868d89c commit 07f04d8
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ Changelog

## HEAD

## 1.0.10 2023-08-27
* add TestingLogWriter helper bridge to `TB.Log*`

## 1.0.9 2023-08-23
* fixes

Expand Down
3 changes: 1 addition & 2 deletions flagset_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package mlog

import (
"fmt"
"io"
"testing"
)
Expand All @@ -12,7 +11,7 @@ func TestFlagSet(t *testing.T) {
expected := Ltimestamp | Ldebug
logger.SetFlags(expected)
flags := logger.Flags()
fmt.Println(flags)
t.Log(flags)
if flags&(expected) == 0 {
t.Errorf("flags did not match\n%12s %#v\n%12s %#v",
"expected:", expected.GoString(),
Expand Down
41 changes: 41 additions & 0 deletions tlogger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright (c) 2012-2016 Eli Janssen
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
//
// some parts from: https://brandur.org/t-parallel

package mlog

import (
"fmt"
"testing"
)

// TestoingLogWriter is an adapter between mlog and Go's testing package,
// which lets us send all output to `t.Log` so that it's correctly
// collated with the test that emitted it. This helps especially when
// using parallel testing where output would otherwise be interleaved
// and make debugging extremely difficult.
type TestingLogWriter struct {
tb testing.TB
}

func (lw *TestingLogWriter) Write(p []byte) (n int, err error) {
// Unfortunately, even with this call to `t.Helper()` there's no
// way to correctly attribute the log location to where it's
// actually emitted in our code (everything shows up under
// `logger.go`). A good explanation of this problem and possible
// future solutions here:
//
// https://github.com/neilotoole/slogt#deficiency
if lw == nil {
return 0, nil
}
if lw.tb == nil {
fmt.Println("got nil testing.TB")
return 0, fmt.Errorf("got a nil testing.TBf")
}
lw.tb.Helper()
lw.tb.Logf(string(p))
return len(p), nil
}
12 changes: 12 additions & 0 deletions tlogger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package mlog

import (
"testing"
)

func TestTLogger(t *testing.T) {
tw := &TestingLogWriter{t}
logger := New(tw, 0)
logger.Info("test")
_ = tw
}

0 comments on commit 07f04d8

Please sign in to comment.