2020-10-27 11:12:40 +00:00
|
|
|
// Copyright (C) 2020 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information
|
|
|
|
|
|
|
|
package testplanet
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
2020-11-03 06:50:24 +00:00
|
|
|
"os"
|
2020-10-27 11:12:40 +00:00
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"go.uber.org/zap/zapcore"
|
2020-11-03 06:50:24 +00:00
|
|
|
"go.uber.org/zap/zaptest"
|
2020-10-27 11:12:40 +00:00
|
|
|
)
|
|
|
|
|
2020-11-03 06:50:24 +00:00
|
|
|
var useAbsTime = os.Getenv("STORJ_TESTPLANET_ABSTIME")
|
|
|
|
|
2022-01-27 11:56:27 +00:00
|
|
|
// NewLogger creates a zaptest logger with nice defaults for tests.
|
|
|
|
func NewLogger(t *testing.T) *zap.Logger {
|
2020-11-03 06:50:24 +00:00
|
|
|
if useAbsTime != "" {
|
|
|
|
return zaptest.NewLogger(t)
|
|
|
|
}
|
|
|
|
|
2020-10-27 11:12:40 +00:00
|
|
|
start := time.Now()
|
|
|
|
cfg := zap.NewDevelopmentEncoderConfig()
|
|
|
|
|
|
|
|
cfg.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
|
|
|
|
var nanos, seconds, minutes int64
|
|
|
|
nanos = t.Sub(start).Nanoseconds()
|
|
|
|
|
|
|
|
seconds, nanos = nanos/1e9, nanos%1e9
|
|
|
|
minutes, seconds = seconds/60, seconds%60
|
|
|
|
|
|
|
|
enc.AppendString(fmt.Sprintf("%02d:%02d.%03d", minutes, seconds, nanos/1e6))
|
|
|
|
}
|
2022-02-10 16:51:19 +00:00
|
|
|
|
2020-10-27 11:12:40 +00:00
|
|
|
enc := zapcore.NewConsoleEncoder(cfg)
|
|
|
|
writer := newTestingWriter(t)
|
2022-02-10 16:51:19 +00:00
|
|
|
level := zapcore.DebugLevel
|
|
|
|
|
|
|
|
if l := os.Getenv("STORJ_TEST_LOG_LEVEL"); l != "" {
|
|
|
|
_ = level.Set(l)
|
|
|
|
}
|
|
|
|
|
2020-10-27 11:12:40 +00:00
|
|
|
return zap.New(
|
2022-02-10 16:51:19 +00:00
|
|
|
zapcore.NewCore(enc, writer, level),
|
2020-10-27 11:12:40 +00:00
|
|
|
zap.ErrorOutput(writer.WithMarkFailed(true)),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
type testingWriter struct {
|
|
|
|
t *testing.T
|
|
|
|
markFailed bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func newTestingWriter(t *testing.T) testingWriter {
|
|
|
|
return testingWriter{t: t}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w testingWriter) WithMarkFailed(v bool) testingWriter {
|
|
|
|
w.markFailed = v
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w testingWriter) Write(p []byte) (n int, err error) {
|
|
|
|
n = len(p)
|
|
|
|
p = bytes.TrimRight(p, "\n")
|
|
|
|
w.t.Logf("%s", p)
|
|
|
|
if w.markFailed {
|
|
|
|
w.t.Fail()
|
|
|
|
}
|
|
|
|
return n, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w testingWriter) Sync() error { return nil }
|