From c88cf7a52dcf9f6ec8dffbb57bd5d71f47c83861 Mon Sep 17 00:00:00 2001 From: Iwasaki Yudai Date: Sun, 20 Sep 2015 13:41:24 +0900 Subject: [PATCH] Show RemoteAddr and HTTP status code in log --- app/app.go | 7 ++++--- app/http_logger.go | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 app/http_logger.go diff --git a/app/app.go b/app/app.go index 790eee6..998c9db 100644 --- a/app/app.go +++ b/app/app.go @@ -218,7 +218,7 @@ func (app *App) handleWS(w http.ResponseWriter, r *http.Request) { conn, err := app.upgrader.Upgrade(w, r, nil) if err != nil { - log.Print("Failed to upgrade connection") + log.Print("Failed to upgrade connection: " + err.Error()) return } @@ -269,8 +269,9 @@ func (app *App) Exit() (firstCall bool) { func wrapLogger(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - log.Printf("%s %s", r.Method, r.URL.Path) - handler.ServeHTTP(w, r) + rw := &responseWrapper{w, 200} + handler.ServeHTTP(rw, r) + log.Printf("%s %d %s %s", r.RemoteAddr, rw.status, r.Method, r.URL.Path) }) } diff --git a/app/http_logger.go b/app/http_logger.go new file mode 100644 index 0000000..8caa803 --- /dev/null +++ b/app/http_logger.go @@ -0,0 +1,23 @@ +package app + +import ( + "bufio" + "net" + "net/http" +) + +type responseWrapper struct { + http.ResponseWriter + status int +} + +func (w *responseWrapper) WriteHeader(status int) { + w.status = status + w.ResponseWriter.WriteHeader(status) +} + +func (w *responseWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { + hj, _ := w.ResponseWriter.(http.Hijacker) + w.status = http.StatusSwitchingProtocols + return hj.Hijack() +}