Created
May 21, 2020 22:18
-
-
Save brianonn/579e083b059773876f669a3154b3250e to your computer and use it in GitHub Desktop.
Run Golang tests, capturing the Uber zap() output to a memory buffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
testwithcapture.go | |
// testWithCapturedZapOutput runs a test and captures zap.L() outputs | |
func testWithCapturedZapOutput(testToRun func(t *testing.T), t *testing.T) string { | |
var buffer bytes.Buffer | |
origLogger := zap.L() | |
defer func() { | |
zap.L().Sync() | |
zap.ReplaceGlobals(origLogger) | |
}() | |
encoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()) | |
writer := bufio.NewWriter(&buffer) | |
logger := zap.New( | |
zapcore.NewCore(encoder, zapcore.AddSync(writer), zapcore.DebugLevel)) | |
zap.ReplaceGlobals(logger) | |
testToRun(t) | |
writer.Flush() | |
return buffer.String() | |
} | |
// add this to top of test function to get zap logging. | |
// then run test with -v (verbose) option | |
oldlogger := zap.L() | |
// reset logger after this test completes | |
defer func() { | |
zap.L().Sync() | |
zap.ReplaceGlobals(oldlogger) | |
}() | |
// create a default logger that writes to stdout, stderr and enables DebugLevel | |
logger, _ := zap.NewDevelopment() | |
zap.ReplaceGlobals(logger) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment