Skip to content

Commit

Permalink
add logger wrapping
Browse files Browse the repository at this point in the history
  • Loading branch information
muir committed Mar 27, 2024
1 parent c6b73a4 commit 3679620
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 2 deletions.
27 changes: 27 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package ntest_test

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/memsql/ntest"
)

var _ ntest.T = &testing.T{}

func TestPrefixLogger(t *testing.T) {
var caught []string
captureT := ntest.ReplaceLogger(t, func(s string) {
t.Log("captured:", s)
caught = append(caught, s)
})
extraDetail := ntest.ExtraDetailLogger(captureT, "some-prefix")
extraDetail.Log("not-formatted", 3)
extraDetail.Logf("formatted '%s'", "quoted")

require.Equal(t, 2, len(caught), "len caught")
assert.Regexp(t, `some-prefix \d\d:\d\d:\d\d not-formatted 3$`, caught[0], "unformatted")
assert.Regexp(t, `some-prefix \d\d:\d\d:\d\d formatted 'quoted'$`, caught[1], "formatted")
}
36 changes: 36 additions & 0 deletions t.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package ntest

import (
"fmt"
"time"
)

// T is subset of what testing.T provides and is also a subset of
// of what ginkgo.GinkgoT() provides. This interface is probably
// richer than strictly required so more could be removed from it
Expand All @@ -21,3 +26,34 @@ type T interface {
Skipf(format string, args ...interface{})
Skipped() bool
}

type logWrappedT struct {
T
logger func(string)
}

// ReplaceLogger creates a T that is wrapped so that the logger is
// overridden with the provided function.
func ReplaceLogger(t T, logger func(string)) T {
return logWrappedT{
T: t,
logger: logger,
}
}

func (t logWrappedT) Log(args ...interface{}) {
line := fmt.Sprintln(args...)
t.logger(line[0 : len(line)-1])
}

func (t logWrappedT) Logf(format string, args ...interface{}) {
t.logger(fmt.Sprintf(format, args...))
}

// ExtraDetailLogger creates a T that wraps the logger to add both a
// prefix and a timestamp to each line that is logged.
func ExtraDetailLogger(t T, prefix string) T {
return ReplaceLogger(t, func(s string) {
t.Log(prefix, time.Now().Format("15:04:05"), s)
})
}
4 changes: 2 additions & 2 deletions test_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import (
"testing"
"time"

"github.com/memsql/ntest"
"github.com/muir/nject"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/memsql/ntest"
)

func TestRun(t *testing.T) {
Expand Down

0 comments on commit 3679620

Please sign in to comment.