github.com/Ilhicas/nomad@v1.0.4-0.20210304152020-e86851182bc3/helper/testlog/testlog.go (about) 1 // Package testlog creates a *log.Logger backed by *testing.T to ease logging 2 // in tests. This allows logs from components being tested to only be printed 3 // if the test fails (or the verbose flag is specified). 4 package testlog 5 6 import ( 7 "bytes" 8 "io" 9 "log" 10 "os" 11 12 hclog "github.com/hashicorp/go-hclog" 13 ) 14 15 // LogPrinter is the methods of testing.T (or testing.B) needed by the test 16 // logger. 17 type LogPrinter interface { 18 Logf(format string, args ...interface{}) 19 } 20 21 // NewWriter creates a new io.Writer backed by a Logger. 22 func NewWriter(t LogPrinter) io.Writer { 23 return os.Stderr 24 } 25 26 // NewPrefixWriter creates a new io.Writer backed by a Logger with a custom 27 // prefix per Write. 28 func NewPrefixWriter(t LogPrinter, prefix string) io.Writer { 29 return &prefixStderr{[]byte(prefix)} 30 } 31 32 // New returns a new test logger. See https://golang.org/pkg/log/#New 33 func New(t LogPrinter, prefix string, flag int) *log.Logger { 34 return log.New(os.Stderr, prefix, flag) 35 } 36 37 // WithPrefix returns a new test logger with the Lmicroseconds flag set. 38 func WithPrefix(t LogPrinter, prefix string) *log.Logger { 39 return New(t, prefix, log.Lmicroseconds) 40 } 41 42 // Logger returns a new test logger with the Lmicroseconds flag set and no 43 // prefix. 44 func Logger(t LogPrinter) *log.Logger { 45 return WithPrefix(t, "") 46 } 47 48 //HCLogger returns a new test hc-logger. 49 func HCLogger(t LogPrinter) hclog.InterceptLogger { 50 level := hclog.Trace 51 envLogLevel := os.Getenv("NOMAD_TEST_LOG_LEVEL") 52 if envLogLevel != "" { 53 level = hclog.LevelFromString(envLogLevel) 54 } 55 opts := &hclog.LoggerOptions{ 56 Level: level, 57 Output: os.Stderr, 58 IncludeLocation: true, 59 } 60 return hclog.NewInterceptLogger(opts) 61 } 62 63 type prefixStderr struct { 64 prefix []byte 65 } 66 67 // Write to stdout with a prefix per call containing non-whitespace characters. 68 func (w *prefixStderr) Write(p []byte) (int, error) { 69 if len(p) == 0 { 70 return 0, nil 71 } 72 73 // Skip prefix if only writing whitespace 74 if len(bytes.TrimSpace(p)) == 0 { 75 return os.Stderr.Write(p) 76 } 77 78 // decrease likely hood of partial line writes that may mess up test 79 // indicator success detection 80 buf := make([]byte, 0, len(w.prefix)+len(p)) 81 buf = append(buf, w.prefix...) 82 buf = append(buf, p...) 83 84 return os.Stderr.Write(buf) 85 }