Skip to content
This repository has been archived by the owner on Mar 16, 2024. It is now read-only.

Commit

Permalink
Merge pull request #75 from tylerslaton/handle-error-fields
Browse files Browse the repository at this point in the history
Offload handleError logging to loggingMiddleware
  • Loading branch information
tylerslaton authored Jul 24, 2023
2 parents 1138dac + 7324d9f commit 39afca9
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
17 changes: 16 additions & 1 deletion pkg/apiserver/logging_middleware.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package apiserver

import (
"encoding/json"
"fmt"
"net"
"net/http"
"runtime/debug"
"strings"
"time"

"github.com/acorn-io/acorn-dns/pkg/model"
"github.com/sirupsen/logrus"
)

Expand All @@ -29,6 +31,7 @@ func realIP(req *http.Request) string {
type responseWriter struct {
http.ResponseWriter
status int
body []byte
wroteHeader bool
}

Expand All @@ -50,6 +53,11 @@ func (rw *responseWriter) WriteHeader(code int) {
rw.wroteHeader = true
}

func (rw *responseWriter) Write(data []byte) (int, error) {
rw.body = append(rw.body, data...)
return rw.ResponseWriter.Write(data)
}

// loggingMiddleware logs the incoming HTTP request & its duration.
func loggingMiddleware(logger *logrus.Entry) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
Expand Down Expand Up @@ -80,7 +88,7 @@ func loggingMiddleware(logger *logrus.Entry) func(http.Handler) http.Handler {

msg := fmt.Sprintf("handled: %d", wrapped.status)
if wrapped.status >= 400 {
requestLogger.Error(msg)
requestLogger.WithFields(logrus.Fields{"error": asErrorResponseModel(wrapped.body).Message}).Errorf(msg)
} else {
requestLogger.Debug(msg)
}
Expand All @@ -90,3 +98,10 @@ func loggingMiddleware(logger *logrus.Entry) func(http.Handler) http.Handler {
return http.HandlerFunc(fn)
}
}

// asErrorResponseModel converts a byte array to an ErrorResponse model if possible
func asErrorResponseModel(data []byte) model.ErrorResponse {
o := model.ErrorResponse{}
_ = json.Unmarshal(data, &o)
return o
}
2 changes: 0 additions & 2 deletions pkg/apiserver/responsewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"net/http"

"github.com/acorn-io/acorn-dns/pkg/model"
"github.com/sirupsen/logrus"
)

func writeErrorResponse(w http.ResponseWriter, httpStatus int, message string, data interface{}) {
Expand All @@ -22,7 +21,6 @@ func writeErrorResponse(w http.ResponseWriter, httpStatus int, message string, d
}

func handleError(w http.ResponseWriter, httpStatus int, err error) {
logrus.Errorf("Error during request: %v", err)
writeErrorResponse(w, httpStatus, err.Error(), nil)
}

Expand Down

0 comments on commit 39afca9

Please sign in to comment.