1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
12 "git.curoverse.com/arvados.git/sdk/go/stats"
13 log "github.com/Sirupsen/logrus"
16 type contextKey struct {
20 var requestTimeContextKey = contextKey{"requestTime"}
22 // LogRequests wraps an http.Handler, logging each request and
23 // response via logrus.
24 func LogRequests(h http.Handler) http.Handler {
25 return http.HandlerFunc(func(wrapped http.ResponseWriter, req *http.Request) {
26 w := &responseTimer{ResponseWriter: WrapResponseWriter(wrapped)}
27 req = req.WithContext(context.WithValue(req.Context(), &requestTimeContextKey, time.Now()))
28 lgr := log.WithFields(log.Fields{
29 "RequestID": req.Header.Get("X-Request-Id"),
30 "remoteAddr": req.RemoteAddr,
31 "reqForwardedFor": req.Header.Get("X-Forwarded-For"),
32 "reqMethod": req.Method,
33 "reqPath": req.URL.Path[1:],
34 "reqBytes": req.ContentLength,
36 logRequest(w, req, lgr)
37 defer logResponse(w, req, lgr)
42 func logRequest(w *responseTimer, req *http.Request, lgr *log.Entry) {
46 func logResponse(w *responseTimer, req *http.Request, lgr *log.Entry) {
47 if tStart, ok := req.Context().Value(&requestTimeContextKey).(time.Time); ok {
49 lgr = lgr.WithFields(log.Fields{
50 "timeTotal": stats.Duration(tDone.Sub(tStart)),
51 "timeToStatus": stats.Duration(w.writeTime.Sub(tStart)),
52 "timeWriteBody": stats.Duration(tDone.Sub(w.writeTime)),
55 lgr.WithFields(log.Fields{
56 "respStatusCode": w.WroteStatus(),
57 "respStatus": http.StatusText(w.WroteStatus()),
58 "respBytes": w.WroteBodyBytes(),
62 type responseTimer struct {
68 func (rt *responseTimer) WriteHeader(code int) {
71 rt.writeTime = time.Now()
73 rt.ResponseWriter.WriteHeader(code)
76 func (rt *responseTimer) Write(p []byte) (int, error) {
79 rt.writeTime = time.Now()
81 return rt.ResponseWriter.Write(p)