github.com/ari-anchor/sei-tendermint@v0.0.0-20230519144642-dc826b7b56bb/libs/log/testing.go (about)

     1  package log
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/rs/zerolog"
     7  )
     8  
     9  // NewTestingLogger converts a testing.T into a logging interface to
    10  // make test failures and verbose provide better feedback associated
    11  // with test failures. This logging instance is safe for use from
    12  // multiple threads, but in general you should create one of these
    13  // loggers ONCE for each *testing.T instance that you interact with.
    14  //
    15  // By default it collects only ERROR messages, or DEBUG messages in
    16  // verbose mode, and relies on the underlying behavior of
    17  // testing.T.Log()
    18  //
    19  // Users should be careful to ensure that no calls to this logger are
    20  // made in goroutines that are running after (which, by the rules of
    21  // testing.TB will panic.)
    22  func NewTestingLogger(t testing.TB) Logger {
    23  	level := LogLevelError
    24  	if testing.Verbose() {
    25  		level = LogLevelDebug
    26  	}
    27  
    28  	return NewTestingLoggerWithLevel(t, level)
    29  }
    30  
    31  // NewTestingLoggerWithLevel creates a testing logger instance at a
    32  // specific level that wraps the behavior of testing.T.Log().
    33  func NewTestingLoggerWithLevel(t testing.TB, level string) Logger {
    34  	logLevel, err := zerolog.ParseLevel(level)
    35  	if err != nil {
    36  		t.Fatalf("failed to parse log level (%s): %v", level, err)
    37  	}
    38  
    39  	return defaultLogger{
    40  		Logger: zerolog.New(newSyncWriter(testingWriter{t})).Level(logLevel),
    41  	}
    42  }
    43  
    44  type testingWriter struct {
    45  	t testing.TB
    46  }
    47  
    48  func (tw testingWriter) Write(in []byte) (int, error) {
    49  	tw.t.Log(string(in))
    50  	return len(in), nil
    51  }