I have so far avoided use of log.Fatal
, but I recently co-incidentally discovered these questions; code-coverage and tests-using-log-fatal.
One of the comments from the 100 code coverage questions says:
... In the vast majority of cases
log.Fatal
should be only be used in main, or init functions (or possibly some things meant to be called only directly from them)"
It go me thinking, so I began to look at the standard library code provided with Go. There are lots of examples where the test code in the library makes use of log.Fatal
which seems fine. There are a few examples outside of the test code, such as in net/http
, shown below:
// net/http/transport.go
func (t *Transport) putIdleConn(pconn *persistConn) bool {
...
for _, exist := range t.idleConn[key] {
if exist == pconn {
log.Fatalf("dup idle pconn %p in freelist", pconn)
}
}
...
}
If its is best practice to avoid use of log.Fatal
, why is it used at all in the standard libraries, I would have expected just return an error. It seems unfair to the user of the library to cause os.Exit
to be called and not providing any chance for the application to clean-up.
I may be naive, so hence my question as a better practice would seem to be to call log.Panic
which can be recovered and my theoretical long running stable application might have a chance of rising from the ashes.
So what would best-practise say for Go about when should log.Fatal should be used?