1
1
package apiserver
2
2
3
3
import (
4
+ "encoding/json"
4
5
"fmt"
5
6
"net"
6
7
"net/http"
7
8
"runtime/debug"
8
9
"strings"
9
10
"time"
10
11
12
+ "github.com/acorn-io/acorn-dns/pkg/model"
11
13
"github.com/sirupsen/logrus"
12
14
)
13
15
@@ -29,6 +31,7 @@ func realIP(req *http.Request) string {
29
31
type responseWriter struct {
30
32
http.ResponseWriter
31
33
status int
34
+ body []byte
32
35
wroteHeader bool
33
36
}
34
37
@@ -50,6 +53,11 @@ func (rw *responseWriter) WriteHeader(code int) {
50
53
rw .wroteHeader = true
51
54
}
52
55
56
+ func (rw * responseWriter ) Write (data []byte ) (int , error ) {
57
+ rw .body = append (rw .body , data ... )
58
+ return rw .ResponseWriter .Write (data )
59
+ }
60
+
53
61
// loggingMiddleware logs the incoming HTTP request & its duration.
54
62
func loggingMiddleware (logger * logrus.Entry ) func (http.Handler ) http.Handler {
55
63
return func (next http.Handler ) http.Handler {
@@ -80,7 +88,7 @@ func loggingMiddleware(logger *logrus.Entry) func(http.Handler) http.Handler {
80
88
81
89
msg := fmt .Sprintf ("handled: %d" , wrapped .status )
82
90
if wrapped .status >= 400 {
83
- requestLogger .Error (msg )
91
+ requestLogger .WithFields (logrus. Fields { "error" : asErrorResponseModel ( wrapped . body ). Message }). Errorf (msg )
84
92
} else {
85
93
requestLogger .Debug (msg )
86
94
}
@@ -90,3 +98,10 @@ func loggingMiddleware(logger *logrus.Entry) func(http.Handler) http.Handler {
90
98
return http .HandlerFunc (fn )
91
99
}
92
100
}
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
+ }
0 commit comments