2019-02-01 15:21:54 +00:00
|
|
|
package testutil
|
|
|
|
|
|
|
|
import (
|
2020-07-21 19:21:52 +00:00
|
|
|
"bytes"
|
2019-02-01 15:21:54 +00:00
|
|
|
"io"
|
2019-02-01 18:25:04 +00:00
|
|
|
"os"
|
2020-07-21 19:21:52 +00:00
|
|
|
"sync"
|
2019-02-01 15:21:54 +00:00
|
|
|
"testing"
|
2020-01-28 23:50:41 +00:00
|
|
|
|
|
|
|
"github.com/hashicorp/go-hclog"
|
2019-02-01 15:21:54 +00:00
|
|
|
)
|
|
|
|
|
2020-01-28 23:50:41 +00:00
|
|
|
func Logger(t testing.TB) hclog.InterceptLogger {
|
2020-07-21 19:21:52 +00:00
|
|
|
return LoggerWithOutput(t, NewLogBuffer(t))
|
2020-01-28 23:50:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func LoggerWithOutput(t testing.TB, output io.Writer) hclog.InterceptLogger {
|
|
|
|
return hclog.NewInterceptLogger(&hclog.LoggerOptions{
|
|
|
|
Name: t.Name(),
|
2020-02-03 14:26:47 +00:00
|
|
|
Level: hclog.Trace,
|
2020-01-28 23:50:41 +00:00
|
|
|
Output: output,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-07-21 19:21:52 +00:00
|
|
|
var sendTestLogsToStdout = os.Getenv("NOLOGBUFFER") == "1"
|
2019-02-01 15:21:54 +00:00
|
|
|
|
2020-07-21 19:21:52 +00:00
|
|
|
// NewLogBuffer returns an io.Writer which buffers all writes. When the test
|
2020-09-04 16:24:11 +00:00
|
|
|
// ends, t.Failed is checked. If the test has failed or has been run in verbose
|
|
|
|
// mode all log output is printed to stdout.
|
2020-07-21 19:21:52 +00:00
|
|
|
//
|
|
|
|
// Set the env var NOLOGBUFFER=1 to disable buffering, resulting in all log
|
|
|
|
// output being written immediately to stdout.
|
|
|
|
func NewLogBuffer(t CleanupT) io.Writer {
|
|
|
|
if sendTestLogsToStdout {
|
|
|
|
return os.Stdout
|
|
|
|
}
|
|
|
|
buf := &logBuffer{buf: new(bytes.Buffer)}
|
|
|
|
t.Cleanup(func() {
|
2020-09-04 16:24:11 +00:00
|
|
|
if t.Failed() || testing.Verbose() {
|
2020-07-21 19:21:52 +00:00
|
|
|
buf.Lock()
|
|
|
|
defer buf.Unlock()
|
|
|
|
buf.buf.WriteTo(os.Stdout)
|
|
|
|
}
|
2020-01-28 23:50:41 +00:00
|
|
|
})
|
2020-07-21 19:21:52 +00:00
|
|
|
return buf
|
2020-01-28 23:50:41 +00:00
|
|
|
}
|
|
|
|
|
2020-07-21 19:21:52 +00:00
|
|
|
type CleanupT interface {
|
|
|
|
Cleanup(f func())
|
|
|
|
Failed() bool
|
2019-02-01 15:21:54 +00:00
|
|
|
}
|
|
|
|
|
2020-07-21 19:21:52 +00:00
|
|
|
type logBuffer struct {
|
|
|
|
buf *bytes.Buffer
|
|
|
|
sync.Mutex
|
2019-02-01 15:21:54 +00:00
|
|
|
}
|
|
|
|
|
2020-07-21 19:21:52 +00:00
|
|
|
func (lb *logBuffer) Write(p []byte) (n int, err error) {
|
|
|
|
lb.Lock()
|
|
|
|
defer lb.Unlock()
|
|
|
|
return lb.buf.Write(p)
|
2019-02-01 15:21:54 +00:00
|
|
|
}
|