Log 404 Status on Missing Files with HTTP File Server
When serving files using http.FileServer, requests for non-existent files can return a 404 status code without being logged on the server console. This can make it challenging to track and troubleshoot missing files.
Solution
To log HTTP 404 errors, enhance the functionality of the handlers returned by http.StripPrefix() and http.FileServer():
The wrapped handler will call the original handler and log HTTP 404 or higher error codes after receiving the response. The example code below demonstrates a complete implementation:
<code class="go">type StatusRespWr struct { http.ResponseWriter status int } func (w *StatusRespWr) WriteHeader(status int) { w.status = status w.ResponseWriter.WriteHeader(status) } func wrapHandler(h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { srw := &StatusRespWr{ResponseWriter: w} h.ServeHTTP(srw, r) if srw.status >= 400 { log.Printf("Error status code: %d when serving path: %s", srw.status, r.RequestURI) } } } func main() { http.HandleFunc("/o/", wrapHandler( http.StripPrefix("/o", http.FileServer(http.Dir("/test"))))) panic(http.ListenAndServe(":8181", nil)) }</code>
When a non-existent file is requested, the wrapped handler will log the following error:
2015/12/01 11:47:40 Error status code: 404 when serving path: /o/sub/b.txt2
The above is the detailed content of How to Log 404 Errors When Using HTTP File Server?. For more information, please follow other related articles on the PHP Chinese website!