Log http requests
This commit is contained in:
parent
f592145b60
commit
e8a65a2770
|
@ -6,6 +6,7 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/julienschmidt/httprouter"
|
"github.com/julienschmidt/httprouter"
|
||||||
|
|
||||||
|
@ -42,7 +43,7 @@ var router = httprouter.New()
|
||||||
func openEndpoint(h handle) httprouter.Handle {
|
func openEndpoint(h handle) httprouter.Handle {
|
||||||
return func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
|
return func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
|
||||||
ctx := contextWithParams(r.Context(), 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
|
// Rendering
|
||||||
//
|
//
|
||||||
|
@ -152,3 +165,13 @@ func (w unbufferedWriter) Write(p []byte) (int, error) {
|
||||||
}
|
}
|
||||||
return n, err
|
return n, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type statusRecorder struct {
|
||||||
|
status int
|
||||||
|
http.ResponseWriter
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w statusRecorder) WriteHeader(statusCode int) {
|
||||||
|
w.status = statusCode
|
||||||
|
w.ResponseWriter.WriteHeader(statusCode)
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue