Skip to content

Commit

Permalink
feat(log): add NewTestLogger{Info,Error} constructors (#15604)
Browse files Browse the repository at this point in the history
  • Loading branch information
mark-rushakoff authored Mar 29, 2023
1 parent ed2eb6f commit a7b80d5
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion log/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,37 @@ type TestingT zerolog.TestingLog

// NewTestLogger returns a logger that calls t.Log to write entries.
//
// The returned logger emits messages at any level.
// For active debugging of a test with verbose logs,
// the [NewTestLoggerInfo] and [NewTestLoggerError] functions
// only emit messages at or above the corresponding log levels.
//
// If the logs may help debug a test failure,
// you may want to use NewTestLogger(t) in your test.
// Otherwise, use NewNopLogger().
func NewTestLogger(t TestingT) Logger {
return newTestLogger(t, zerolog.DebugLevel)
}

// NewTestLoggerInfo returns a test logger that filters out messages
// below info level.
//
// This is primarily helpful during active debugging of a test
// with verbose logs.
func NewTestLoggerInfo(t TestingT) Logger {
return newTestLogger(t, zerolog.InfoLevel)
}

// NewTestLoggerError returns a test logger that filters out messages
// below Error level.
//
// This is primarily helpful during active debugging of a test
// with verbose logs.
func NewTestLoggerError(t TestingT) Logger {
return newTestLogger(t, zerolog.ErrorLevel)
}

func newTestLogger(t TestingT, lvl zerolog.Level) Logger {
cw := zerolog.NewConsoleWriter()
cw.Out = zerolog.TestWriter{
T: t,
Expand All @@ -22,5 +49,5 @@ func NewTestLogger(t TestingT) Logger {
// but Frame=7 prints correct source locations.
Frame: 7,
}
return NewCustomLogger(zerolog.New(cw))
return NewCustomLogger(zerolog.New(cw).Level(lvl))
}

0 comments on commit a7b80d5

Please sign in to comment.