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

Commit 39afca9

Browse files
authored
Merge pull request #75 from tylerslaton/handle-error-fields
Offload handleError logging to loggingMiddleware
2 parents 1138dac + 7324d9f commit 39afca9

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

pkg/apiserver/logging_middleware.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
package apiserver
22

33
import (
4+
"encoding/json"
45
"fmt"
56
"net"
67
"net/http"
78
"runtime/debug"
89
"strings"
910
"time"
1011

12+
"github.com/acorn-io/acorn-dns/pkg/model"
1113
"github.com/sirupsen/logrus"
1214
)
1315

@@ -29,6 +31,7 @@ func realIP(req *http.Request) string {
2931
type responseWriter struct {
3032
http.ResponseWriter
3133
status int
34+
body []byte
3235
wroteHeader bool
3336
}
3437

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

56+
func (rw *responseWriter) Write(data []byte) (int, error) {
57+
rw.body = append(rw.body, data...)
58+
return rw.ResponseWriter.Write(data)
59+
}
60+
5361
// loggingMiddleware logs the incoming HTTP request & its duration.
5462
func loggingMiddleware(logger *logrus.Entry) func(http.Handler) http.Handler {
5563
return func(next http.Handler) http.Handler {
@@ -80,7 +88,7 @@ func loggingMiddleware(logger *logrus.Entry) func(http.Handler) http.Handler {
8088

8189
msg := fmt.Sprintf("handled: %d", wrapped.status)
8290
if wrapped.status >= 400 {
83-
requestLogger.Error(msg)
91+
requestLogger.WithFields(logrus.Fields{"error": asErrorResponseModel(wrapped.body).Message}).Errorf(msg)
8492
} else {
8593
requestLogger.Debug(msg)
8694
}
@@ -90,3 +98,10 @@ func loggingMiddleware(logger *logrus.Entry) func(http.Handler) http.Handler {
9098
return http.HandlerFunc(fn)
9199
}
92100
}
101+
102+
// asErrorResponseModel converts a byte array to an ErrorResponse model if possible
103+
func asErrorResponseModel(data []byte) model.ErrorResponse {
104+
o := model.ErrorResponse{}
105+
_ = json.Unmarshal(data, &o)
106+
return o
107+
}

pkg/apiserver/responsewriter.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"net/http"
66

77
"github.com/acorn-io/acorn-dns/pkg/model"
8-
"github.com/sirupsen/logrus"
98
)
109

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

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

0 commit comments

Comments
 (0)