diff --git a/middleware/log/log.go b/middleware/log/log.go index f4329d21..7c206458 100644 --- a/middleware/log/log.go +++ b/middleware/log/log.go @@ -2,6 +2,7 @@ package log import ( + "fmt" "log" "net/http" @@ -19,6 +20,11 @@ func (l Logger) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { if middleware.Path(r.URL.Path).Matches(rule.PathScope) { responseRecorder := middleware.NewResponseRecorder(w) status, err := l.Next.ServeHTTP(responseRecorder, r) + if status >= 400 { + responseRecorder.WriteHeader(status) + fmt.Fprintf(responseRecorder, "%d %s", status, http.StatusText(status)) + status = 0 + } rep := middleware.NewReplacer(r, responseRecorder) rule.Log.Println(rep.Replace(rule.Format)) return status, err diff --git a/middleware/log/log_test.go b/middleware/log/log_test.go new file mode 100644 index 00000000..40560e4c --- /dev/null +++ b/middleware/log/log_test.go @@ -0,0 +1,48 @@ +package log + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +type erroringMiddleware struct{} + +func (erroringMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { + return http.StatusNotFound, nil +} + +func TestLoggedStatus(t *testing.T) { + var f bytes.Buffer + var next erroringMiddleware + rule := Rule{ + PathScope: "/", + Format: DefaultLogFormat, + Log: log.New(&f, "", 0), + } + + logger := Logger{ + Rules: []Rule{rule}, + Next: next, + } + + r, err := http.NewRequest("GET", "/", nil) + if err != nil { + t.Fatal(err) + } + + rec := httptest.NewRecorder() + + status, err := logger.ServeHTTP(rec, r) + if status != 0 { + t.Error("Expected status to be 0 - was", status) + } + + logged := f.String() + if !strings.Contains(logged, "404 13") { + t.Error("Expected 404 to be logged. Logged string -", logged) + } +}