You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.4 KiB

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