|
6 | 6 | "fmt" |
7 | 7 | "log/slog" |
8 | 8 | "net/http" |
9 | | - "os" |
| 9 | + "time" |
10 | 10 |
|
11 | | - "github.com/gorilla/handlers" |
12 | 11 | "github.com/gorilla/mux" |
13 | 12 |
|
14 | 13 | "github.com/sysdiglabs/harbor-scanner-sysdig-secure/pkg/harbor" |
@@ -36,7 +35,7 @@ func NewAPIHandler(adapter scanner.Adapter) http.Handler { |
36 | 35 | apiV1Router.Methods(http.MethodPost).Path("/scan").HandlerFunc(handler.scan) |
37 | 36 | apiV1Router.Methods(http.MethodGet).Path("/scan/{scan_request_id}/report").HandlerFunc(handler.getReport) |
38 | 37 |
|
39 | | - return handlers.LoggingHandler(os.Stdout, router) |
| 38 | + return loggingMiddleware(router) |
40 | 39 | } |
41 | 40 |
|
42 | 41 | func health(res http.ResponseWriter, _ *http.Request) { |
@@ -127,6 +126,38 @@ func (h *requestHandler) getReport(res http.ResponseWriter, req *http.Request) { |
127 | 126 | _ = json.NewEncoder(res).Encode(vulnerabilityReport) |
128 | 127 | } |
129 | 128 |
|
| 129 | +type statusRecorder struct { |
| 130 | + http.ResponseWriter |
| 131 | + status int |
| 132 | + size int |
| 133 | +} |
| 134 | + |
| 135 | +func (r *statusRecorder) WriteHeader(code int) { |
| 136 | + r.status = code |
| 137 | + r.ResponseWriter.WriteHeader(code) |
| 138 | +} |
| 139 | + |
| 140 | +func (r *statusRecorder) Write(b []byte) (int, error) { |
| 141 | + n, err := r.ResponseWriter.Write(b) |
| 142 | + r.size += n |
| 143 | + return n, err |
| 144 | +} |
| 145 | + |
| 146 | +func loggingMiddleware(next http.Handler) http.Handler { |
| 147 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 148 | + rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK} |
| 149 | + start := time.Now() |
| 150 | + next.ServeHTTP(rec, r) |
| 151 | + slog.Info("http request", |
| 152 | + "method", r.Method, |
| 153 | + "path", r.RequestURI, |
| 154 | + "status", rec.status, |
| 155 | + "size", rec.size, |
| 156 | + "duration", time.Since(start), |
| 157 | + ) |
| 158 | + }) |
| 159 | +} |
| 160 | + |
130 | 161 | func errorResponseFromError(err error) harbor.ErrorResponse { |
131 | 162 | return harbor.ErrorResponse{ |
132 | 163 | Error: &harbor.ModelError{ |
|
0 commit comments