From e8a65a27709b0ef8165fa3c1898e419015edb5b3 Mon Sep 17 00:00:00 2001 From: Gregory Eremin Date: Fri, 7 Sep 2018 15:16:39 +0200 Subject: [PATCH] Log http requests --- backend/api/api.go | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/backend/api/api.go b/backend/api/api.go index aeb949c..19a32aa 100644 --- a/backend/api/api.go +++ b/backend/api/api.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "strconv" + "time" "github.com/julienschmidt/httprouter" @@ -42,7 +43,7 @@ var router = httprouter.New() func openEndpoint(h handle) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, params httprouter.Params) { ctx := contextWithParams(r.Context(), params) - h(ctx, w, r) + logRequest(ctx, w, r, h) } } @@ -59,6 +60,18 @@ func protectedEndpoint(h handle) httprouter.Handle { } } +func logRequest(ctx context.Context, w http.ResponseWriter, r *http.Request, h handle) { + startedAt := time.Now() + log.Logger().Infof("--> %s %s", r.Method, r.URL.Path) + sw := statusRecorder{ResponseWriter: w} + h(ctx, sw, r) + took := time.Since(startedAt).Truncate(100 * time.Microsecond) + if sw.status == 0 { + sw.status = http.StatusOK + } + log.Logger().Infof("<-- %d %s (%s)", sw.status, http.StatusText(sw.status), took) +} + // // Rendering // @@ -152,3 +165,13 @@ func (w unbufferedWriter) Write(p []byte) (int, error) { } return n, err } + +type statusRecorder struct { + status int + http.ResponseWriter +} + +func (w statusRecorder) WriteHeader(statusCode int) { + w.status = statusCode + w.ResponseWriter.WriteHeader(statusCode) +}