2019-02-01 15:21:54 +00:00
|
|
|
package testutil
|
|
|
|
|
|
|
|
import (
|
2020-05-06 20:40:16 +00:00
|
|
|
"bytes"
|
2019-02-01 15:21:54 +00:00
|
|
|
"io"
|
2019-02-01 18:25:04 +00:00
|
|
|
"os"
|
2020-05-06 20:40:16 +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-09-10 13:04:56 +00:00
|
|
|
func Logger(t TestingTB) hclog.InterceptLogger {
|
2020-05-06 20:40:16 +00:00
|
|
|
return LoggerWithOutput(t, NewLogBuffer(t))
|
2020-01-28 23:50:41 +00:00
|
|
|
}
|
|
|
|
|
2020-09-10 13:04:56 +00:00
|
|
|
func LoggerWithOutput(t TestingTB, output io.Writer) hclog.InterceptLogger {
|
2020-01-28 23:50:41 +00:00
|
|
|
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-05-06 20:40:16 +00:00
|
|
|
var sendTestLogsToStdout = os.Getenv("NOLOGBUFFER") == "1"
|
2019-02-01 15:21:54 +00:00
|
|
|
|
2020-05-06 20:40:16 +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-05-06 20:40:16 +00:00
|
|
|
//
|
|
|
|
// Set the env var NOLOGBUFFER=1 to disable buffering, resulting in all log
|
|
|
|
// output being written immediately to stdout.
|
2020-09-10 13:04:56 +00:00
|
|
|
func NewLogBuffer(t TestingTB) io.Writer {
|
2020-05-06 20:40:16 +00:00
|
|
|
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-05-06 20:40:16 +00:00
|
|
|
buf.Lock()
|
|
|
|
defer buf.Unlock()
|
|
|
|
buf.buf.WriteTo(os.Stdout)
|
|
|
|
}
|
2020-01-28 23:50:41 +00:00
|
|
|
})
|
2020-05-06 20:40:16 +00:00
|
|
|
return buf
|
2020-01-28 23:50:41 +00:00
|
|
|
}
|
|
|
|
|
2020-05-06 20:40:16 +00:00
|
|
|
type logBuffer struct {
|
|
|
|
buf *bytes.Buffer
|
|
|
|
sync.Mutex
|
2019-02-01 15:21:54 +00:00
|
|
|
}
|
|
|
|
|
2020-05-06 20:40:16 +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
|
|
|
}
|