I'm learning Go and came across this behavior I don't understand. When I do error checking and use log.Printf() I see the os error that I would normally see if I make that same error on the command line.
But when I use log.Fatal() the last log.Printf() does not print to the screen.
package main
import (
"log"
"os/exec"
"fmt"
)
func main() {
cmd := exec.Command("ls", "-2")
stdoutStderr, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error: %v", err)
fmt.Println("Printing log fatal()")
log.Fatal(err)
}
fmt.Printf("Output %s
", stdoutStderr)
}
I was expecting to see this output:
# go run main.go
2019/05/14 11:23:34 Error: exit status 2
Output ls: invalid option -- '2'
Try 'ls --help' for more information.
Printing log fatal()
2019/05/14 11:24:45 exit status 2
exit status 1
But My actual result is:
# go run main.go
2019/05/14 11:24:45 Error: exit status 2
Printing log fata()
2019/05/14 11:24:45 exit status 2
exit status 1
log.Fatal
calls os.Exit()
after printing the log message. So statements after log.Fatal()
will not be called. I believe that is the reason you are not seeing output of fmt.Printf("Output %s ", stdoutStderr)
in the logs.