MockLog provides the ability to capture log output.
It contains an ldlog.Loggers instance which can be used like any other Loggers, but all of the output is captured by the enclosing MockLog and can be retrieved with the MockLog methods.
mockLog := ldlogtest.NewMockLog() mockLog.Loggers.Warn("message") mockLog.Loggers.Warnf("also: %t", true) warnMessages := mockLog.GetOutput(ldlog.Warn) // returns {"message", "also: true"}
type MockLog struct { // Loggers is the ldlog.Loggers instance to be used for tests. Loggers ldlog.Loggers // contains filtered or unexported fields }
func NewMockLog() *MockLog
NewMockLog creates a log-capturing object.
func (ml *MockLog) AssertMessageMatch(t *testing.T, shouldMatch bool, level ldlog.LogLevel, pattern string)
AssertMessageMatch asserts whether there is a log message of this level that matches this regex. This is equivalent to using assert.True or assert.False with MockLog.HasMessageMatch, except that if the test fails, it includes the actual log messages in the failure message.
func (ml *MockLog) Dump(w io.Writer)
Dump is a shortcut for writing all captured log lines to a Writer.
func (ml *MockLog) DumpIfTestFailed(t *testing.T)
DumpIfTestFailed is a shortcut for writing all captured log lines to standard output only if t.Failed() is true.
This is useful in tests where you normally don't want to see the log output, but you do want to see it if there was a failure. The simplest way to do this is to use defer:
func TestSomething(t *testing.T) { ml := ldlogtest.NewMockLog() defer ml.DumpIfTestFailed(t) // ... do some test things that may generate log output and/or cause a failure }
func (ml *MockLog) GetAllOutput() []MockLogItem
GetAllOutput returns the captured output for all log levels.
func (ml *MockLog) GetOutput(level ldlog.LogLevel) []string
GetOutput returns the captured output for a specific log level.
func (ml *MockLog) HasMessageMatch(level ldlog.LogLevel, pattern string) bool
HasMessageMatch tests whether there is a log message of this level that matches this regex.
MockLogItem represents a log message captured by MockLog.
type MockLogItem struct { Level ldlog.LogLevel Message string }