2018-01-08 21:36:07 +00:00
|
|
|
// Package testlog creates a *log.Logger backed by *testing.T to ease logging
|
|
|
|
// in tests. This allows logs from components being tested to only be printed
|
|
|
|
// if the test fails (or the verbose flag is specified).
|
2018-01-08 20:53:58 +00:00
|
|
|
package testlog
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
)
|
|
|
|
|
2018-01-08 21:36:07 +00:00
|
|
|
// LogPrinter is the methods of testing.T (or testing.B) needed by the test
|
2018-01-08 20:53:58 +00:00
|
|
|
// logger.
|
2018-01-08 21:36:07 +00:00
|
|
|
type LogPrinter interface {
|
2018-01-08 20:53:58 +00:00
|
|
|
Logf(format string, args ...interface{})
|
|
|
|
}
|
|
|
|
|
|
|
|
// writer implements io.Writer on top of a Logger.
|
|
|
|
type writer struct {
|
2018-01-08 21:36:07 +00:00
|
|
|
t LogPrinter
|
2018-01-08 20:53:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Write to an underlying Logger. Never returns an error.
|
|
|
|
func (w *writer) Write(p []byte) (n int, err error) {
|
|
|
|
w.t.Logf(string(p))
|
|
|
|
return len(p), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewWriter creates a new io.Writer backed by a Logger.
|
2018-01-08 21:36:07 +00:00
|
|
|
func NewWriter(t LogPrinter) io.Writer {
|
2018-01-08 20:53:58 +00:00
|
|
|
return &writer{t}
|
|
|
|
}
|
|
|
|
|
2018-01-08 21:36:07 +00:00
|
|
|
// New returns a new test logger. See https://golang.org/pkg/log/#New
|
|
|
|
func New(t LogPrinter, prefix string, flag int) *log.Logger {
|
2018-01-08 20:53:58 +00:00
|
|
|
return log.New(&writer{t}, prefix, flag)
|
|
|
|
}
|
|
|
|
|
2018-01-08 21:36:07 +00:00
|
|
|
// WithPrefix returns a new test logger with the Lmicroseconds flag set.
|
|
|
|
func WithPrefix(t LogPrinter, prefix string) *log.Logger {
|
|
|
|
return New(t, prefix, log.Lmicroseconds)
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewLog logger with "TEST" prefix and the Lmicroseconds flag.
|
|
|
|
func Logger(t LogPrinter) *log.Logger {
|
|
|
|
return WithPrefix(t, "TEST ")
|
2018-01-08 20:53:58 +00:00
|
|
|
}
|