'What errors are outputted to http.Server's ErrorLog struct field?
I'm trying to understand the purpose of an ErrorLog struct field in http.Server struct. By its name I suspect that those are some kind of errors, but which ones?
What would trigger errors being outputted there? Broken network? Too large http requests?
package main
import (
"log"
"net/http"
)
func main() {
_ = &http.Server{
ErrorLog: log.Default(), // what errors are outputted here?
}
}
Solution 1:[1]
The official documentation provides an overview of how the field is used:
// ErrorLog specifies an optional logger for errors accepting
// connections, unexpected behavior from handlers, and
// underlying FileSystem errors.
// If nil, logging is done via the log package's standard logger.
ErrorLog *log.Logger // Go 1.3
In practice, the field is accessed in the *http.Server's logf method. You can check where that method is called. In short (not exhaustive):
- on panics serving HTTP requests (
conn'sserve(ctx context.Context)) - on TLS handshake errors
- on the server's
Serve(l net.Listener) errorerrors - on writing non-empty data to the response, if the connection was hijacked
- if the
Content-Lengthis invalid - if you call
WriteHeader(code int)on the same response more than once - if
Content-Lengthand non-identityTransfer-Encodingheaders are used together
Solution 2:[2]
type serverErrorLogWriter struct{}
func (*serverErrorLogWriter) Write(p []byte) (int, error) {
m := string(p)
if strings.HasPrefix(m, "http: TLS handshake error") && strings.HasSuffix(m, ": EOF\n") {
// handle EOF error
} else {
// handle other errors
}
return len(p), nil
}
func newServerErrorLog() *log.Logger {
return log.New(&serverErrorLogWriter{}, "", 0)
}
And then
ErrorLog: log.New(&serverErrorLogWriter{}, "", 0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | blackgreen |
| Solution 2 | Nizar |
