Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add check for internal server to do error log #625

Merged
merged 3 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion pkg/gofr/http/middleware/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,13 @@ func Logging(logger logger) func(inner http.Handler) http.Handler {
URI: req.RequestURI,
Response: res.status,
}

if logger != nil {
logger.Log(l)
if res.status >= http.StatusInternalServerError {
logger.Error(l)
} else {
logger.Log(l)
}
}
}(srw, r)

Expand Down
20 changes: 20 additions & 0 deletions pkg/gofr/http/middleware/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading