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.

60 lines
1.8 KiB

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