Based off the configurations for zap.NewDevelopmentConfig()
and zap.NewProductionConfig()
, I've assumed that zap writes logs to stderr
. However, I can't seem to capture the output in unit tests.
I have the following captureOutput
func:
func captureOutput(f func()) string {
r, w, err := os.Pipe()
if err != nil {
panic(err)
}
stdout := os.Stdout
os.Stdout = w
defer func() {
os.Stdout = stdout
}()
stderr := os.Stderr
os.Stderr = w
defer func() {
os.Stderr = stderr
}()
f()
w.Close()
var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String()
}
It fails to capture zap output but does manage to grab output from fmt.Println(...)
:
func TestZapCapture(t *testing.T) {
auditor, _ := zap.NewProduction()
output := captureOutput(func() {
auditor.Info("hi")
})
assert.NotEmpty(t, output)
//fails to captures output
}
func TestFmtCapture(t *testing.T) {
output := captureOutput(func() {
fmt.Println("hi")
})
assert.NotEmpty(t, output)
//successfully captures output
}
I'm aware of using the zap observer for situations like this but my real use case is to test a highly modified zap logger so testing a new zap.Core
would defeat the purpose. Whats the best way to capture that output?