From 3be1724196683376f67e3fc62862f104fb147e53 Mon Sep 17 00:00:00 2001 From: vipul-rawat Date: Thu, 16 May 2024 11:19:09 +0530 Subject: [PATCH 1/2] add check for internal server to do error log --- pkg/gofr/http/middleware/logger.go | 6 +++++- pkg/gofr/http/middleware/logger_test.go | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/pkg/gofr/http/middleware/logger.go b/pkg/gofr/http/middleware/logger.go index d79bad327..678adb9fa 100644 --- a/pkg/gofr/http/middleware/logger.go +++ b/pkg/gofr/http/middleware/logger.go @@ -89,7 +89,11 @@ func Logging(logger logger) func(inner http.Handler) http.Handler { Response: res.status, } if logger != nil { - logger.Log(l) + if res.status >= http.StatusInternalServerError { + logger.Error(l) + } else { + logger.Log(l) + } } }(srw, r) diff --git a/pkg/gofr/http/middleware/logger_test.go b/pkg/gofr/http/middleware/logger_test.go index 61a86e3f6..cdd974b8f 100644 --- a/pkg/gofr/http/middleware/logger_test.go +++ b/pkg/gofr/http/middleware/logger_test.go @@ -55,12 +55,32 @@ func Test_LoggingMiddleware(t *testing.T) { assert.Contains(t, logs, "GET 200") } +func Test_LoggingMiddlewareError(t *testing.T) { + logs := testutil.StderrOutputForFunc(func() { + req, _ := http.NewRequestWithContext(context.Background(), "GET", "http://dummy", http.NoBody) + + rr := httptest.NewRecorder() + + handler := Logging(logging.NewMockLogger(logging.ERROR))(http.HandlerFunc(testHandlerError)) + + handler.ServeHTTP(rr, req) + }) + + assert.Contains(t, logs, "GET 500") +} + // Test handler that uses the middleware. func testHandler(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte("Test Handler")) } +// Test handler for internalServerErrors that uses the middleware. +func testHandlerError(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte("error")) +} + func Test_LoggingMiddlewareStringPanicHandling(t *testing.T) { logs := testutil.StderrOutputForFunc(func() { req, _ := http.NewRequestWithContext(context.Background(), "GET", "http://dummy", http.NoBody) From b5a122f964b31410783d8c3d94cb62835ff9e78c Mon Sep 17 00:00:00 2001 From: vipul-rawat Date: Thu, 16 May 2024 11:35:51 +0530 Subject: [PATCH 2/2] linter fix --- pkg/gofr/http/middleware/logger.go | 1 + 1 file changed, 1 insertion(+) diff --git a/pkg/gofr/http/middleware/logger.go b/pkg/gofr/http/middleware/logger.go index 678adb9fa..fbfa0b968 100644 --- a/pkg/gofr/http/middleware/logger.go +++ b/pkg/gofr/http/middleware/logger.go @@ -88,6 +88,7 @@ func Logging(logger logger) func(inner http.Handler) http.Handler { URI: req.RequestURI, Response: res.status, } + if logger != nil { if res.status >= http.StatusInternalServerError { logger.Error(l)