Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

Should a Go package ever use log.Fatal and when?

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?

question from:https://stackoverflow.com/questions/33885235/should-a-go-package-ever-use-log-fatal-and-when

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...