Add HTTP status code to logs

This adds the status code to the response log message to make it easier
to diagnose issues. It also replaces the placeholder "Success" message
with the decoded value of the HTTP Status, resulting in messages like:

INFO[0041] Response: Temporary Redirect                  code=307

...and so on. Both easily consumable by humans and machines.
pull/10616/head
Tim Raymond 2017-05-05 18:13:54 -04:00
parent bdf111357d
commit ee5760bfd3
1 changed files with 16 additions and 2 deletions

View File

@ -7,6 +7,17 @@ import (
"github.com/influxdata/chronograf"
)
type logResponseWriter struct {
http.ResponseWriter
responseCode int
}
func (l *logResponseWriter) WriteHeader(status int) {
l.responseCode = status
l.ResponseWriter.WriteHeader(status)
}
// Logger is middleware that logs the request
func Logger(logger chronograf.Logger, next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
@ -17,7 +28,9 @@ func Logger(logger chronograf.Logger, next http.Handler) http.Handler {
WithField("method", r.Method).
WithField("url", r.URL).
Info("Request")
next.ServeHTTP(w, r)
lrr := &logResponseWriter{w, 0}
next.ServeHTTP(lrr, r)
later := time.Now()
elapsed := later.Sub(now)
@ -25,7 +38,8 @@ func Logger(logger chronograf.Logger, next http.Handler) http.Handler {
WithField("component", "server").
WithField("remote_addr", r.RemoteAddr).
WithField("response_time", elapsed.String()).
Info("Success")
WithField("code", lrr.responseCode).
Info("Response: ", http.StatusText(lrr.responseCode))
}
return http.HandlerFunc(fn)
}