Browse Source

testing,log: add testing.T logger connector (#7447)

pull/7449/head
Sam Kleinman 3 years ago
committed by GitHub
parent
commit
f56df58fe8
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 50 additions and 6 deletions
  1. +50
    -6
      libs/log/testing.go

+ 50
- 6
libs/log/testing.go View File

@ -1,10 +1,10 @@
package log package log
import ( import (
"io"
"os"
"sync" "sync"
"testing" "testing"
"github.com/rs/zerolog"
) )
var ( var (
@ -19,11 +19,11 @@ var (
// NOTE: // NOTE:
// - A call to NewTestingLogger() must be made inside a test (not in the init func) // - A call to NewTestingLogger() must be made inside a test (not in the init func)
// because verbose flag only set at the time of testing. // because verbose flag only set at the time of testing.
// - Repeated calls to this function within a single process will
// produce a single test log instance, and while the logger is safe
// for parallel use it it doesn't produce meaningful feedback for
// parallel tests.
func TestingLogger() Logger { func TestingLogger() Logger {
return TestingLoggerWithOutput(os.Stdout)
}
func TestingLoggerWithOutput(w io.Writer) Logger {
testingLoggerMtx.Lock() testingLoggerMtx.Lock()
defer testingLoggerMtx.Unlock() defer testingLoggerMtx.Unlock()
@ -39,3 +39,47 @@ func TestingLoggerWithOutput(w io.Writer) Logger {
return testingLogger return testingLogger
} }
type testingWriter struct {
t testing.TB
}
func (tw testingWriter) Write(in []byte) (int, error) {
tw.t.Log(string(in))
return len(in), nil
}
// NewTestingLogger converts a testing.T into a logging interface to
// make test failures and verbose provide better feedback associated
// with test failures. This logging instance is safe for use from
// multiple threads, but in general you should create one of these
// loggers ONCE for each *testing.T instance that you interact with.
//
// By default it collects only ERROR messages, or DEBUG messages in
// verbose mode, and relies on the underlying behavior of testing.T.Log()
func NewTestingLogger(t testing.TB) Logger {
level := LogLevelError
if testing.Verbose() {
level = LogLevelDebug
}
return NewTestingLoggerWithLevel(t, level)
}
// NewTestingLoggerWithLevel creates a testing logger instance at a
// specific level that wraps the behavior of testing.T.Log().
func NewTestingLoggerWithLevel(t testing.TB, level string) Logger {
logLevel, err := zerolog.ParseLevel(level)
if err != nil {
t.Fatalf("failed to parse log level (%s): %v", level, err)
}
trace := false
if testing.Verbose() {
trace = true
}
return defaultLogger{
Logger: zerolog.New(newSyncWriter(testingWriter{t})).Level(logLevel),
trace: trace,
}
}

Loading…
Cancel
Save