-
-
Save logie17/3e79f010db4c6b4c714d to your computer and use it in GitHub Desktop.
var logLines []string | |
type logMock struct{} | |
func (l *logMock) Write(p []byte) (int, error) { | |
logLines = append(logLines, string(p)) | |
return 0, nil | |
} | |
//CaptureLogOutput A utility to capture the log output of a function and pass it along | |
func CaptureLogOutput(toBeCaptured func(), handleResults func([]string)) { | |
logLines = []string{} | |
currentFlags := log.Flags() | |
log.SetFlags(0) | |
log.SetOutput(&logMock{}) | |
toBeCaptured() | |
log.SetOutput(os.Stderr) | |
log.SetFlags(currentFlags) | |
handleResults(logLines) | |
} |
What happens if toBeCaptured()
crashes or causes the program to exit? Would log.SetOutput(os.Stderr)
still happen? I'd expect to see defer
being used here.
Yeah, good point.. further iterations to follow
It would also be handy if the return value of CaptureLogOutput
were the return value of the func
that it encloses. That would allow you to do things like:
got := CaptureLogOutput(func() rune {
log.Print("about to return something")
return "☃"
},
func(logs []string) {
// assert something about what got logged
})
// assert something about the return value "☃"
This may be a can of worms since the return value of CaptureLogOutput then becomes subject to the whims of the code that's being wrapped. So maybe another callback?
CaptureLogOutput(func() rune {
log.Print("about to return something")
return "☃"
},
func(logs []string) {
// assert something about what got logged
},
func(frosty rune) {
// assert frosty is "☃"
})
Making the callback to test the return value of the wrapped function be the third argument to CaptureLogOutput
feels sensible since not all code run in CaptureLogOutput
will actually have a return value, so that avoids needing to pass in an empty function as a second argument.
Great idea, all ideas implemented: https://github.com/MediaMath/auth_go_common_libs
The following then can be done: