Using Cobra I want all output to be in my structured logging format.
The problem is in order to use SetOut()
and SetErr()
in my tests I need to send output like this:
fmt.Fprint(cmd.OutOrStderr(), "my output")
fmt.Fprint(cmd.OutOrStdout(), "my output")
This is how I'm doing this now and it works, but I want to know if there is a simpler way:
// Use buffers to capture log output to manually send it through cmd methods
var (
stdout = bytes.NewBufferString("")
stderr = bytes.NewBufferString("")
lout = slog.New(slog.NewJSONHandler(bout, nil))
lerr = slog.New(slog.NewJSONHandler(berr, nil))
)
.......
// Log to the buffers and then redirect through cmd
lout.Info("my stdout output")
sout, _ := io.ReadAll(stdout)
fmt.Fprint(cmd.OutOrStdout(), string(sout))
lerr.Info("my stderr output")
lerr, _ := io.ReadAll(stderr)
fmt.Fprint(cmd.OutOrStderr(), string(lerr))
Now in my tests I can properly capture output like this:
b := bytes.NewBufferString("")
cmd.SetOut(b)
cmd.SetErr(b)
This works, but it feels like I'm doing more work then I need to do.
All I want is for my cobra output to be in my slogger format and be able to use SetOut()
and SetErr()
in my tests to redirect output as needed.