github.com/vnforks/kid@v5.11.1+incompatible/mlog/testing.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See License.txt for license information. 3 4 package mlog 5 6 import ( 7 "strings" 8 "testing" 9 10 "go.uber.org/zap" 11 "go.uber.org/zap/zapcore" 12 ) 13 14 // testingWriter is an io.Writer that writes through t.Log 15 type testingWriter struct { 16 tb testing.TB 17 } 18 19 func (tw *testingWriter) Write(b []byte) (int, error) { 20 tw.tb.Log(strings.TrimSpace(string(b))) 21 return len(b), nil 22 } 23 24 // NewTestingLogger creates a Logger that proxies logs through a testing interface. 25 // This allows tests that spin up App instances to avoid spewing logs unless the test fails or -verbose is specified. 26 func NewTestingLogger(tb testing.TB) *Logger { 27 logWriter := &testingWriter{tb} 28 logWriterSync := zapcore.AddSync(logWriter) 29 30 testingLogger := &Logger{ 31 consoleLevel: zap.NewAtomicLevelAt(getZapLevel("debug")), 32 fileLevel: zap.NewAtomicLevelAt(getZapLevel("info")), 33 } 34 35 logWriterCore := zapcore.NewCore(makeEncoder(true), logWriterSync, testingLogger.consoleLevel) 36 37 testingLogger.zap = zap.New(logWriterCore, 38 zap.AddCaller(), 39 ) 40 return testingLogger 41 }