X-Git-Url: https://git.arvados.org/arvados.git/blobdiff_plain/0d50e82dd2255104e60c0882045b54774e1be380..8a879fd6ffb38927150be85c63d926cd6a4c0d42:/sdk/go/httpserver/logger.go diff --git a/sdk/go/httpserver/logger.go b/sdk/go/httpserver/logger.go index 1a4b7c5592..f64708454c 100644 --- a/sdk/go/httpserver/logger.go +++ b/sdk/go/httpserver/logger.go @@ -9,25 +9,34 @@ import ( "net/http" "time" + "git.curoverse.com/arvados.git/sdk/go/ctxlog" "git.curoverse.com/arvados.git/sdk/go/stats" - "github.com/Sirupsen/logrus" + "github.com/sirupsen/logrus" ) type contextKey struct { name string } -var requestTimeContextKey = contextKey{"requestTime"} +var ( + requestTimeContextKey = contextKey{"requestTime"} +) -var Logger logrus.FieldLogger = logrus.StandardLogger() +// HandlerWithContext returns an http.Handler that changes the request +// context to ctx (replacing http.Server's default +// context.Background()), then calls next. +func HandlerWithContext(ctx context.Context, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} // LogRequests wraps an http.Handler, logging each request and -// response via logrus. +// response. func LogRequests(h http.Handler) http.Handler { return http.HandlerFunc(func(wrapped http.ResponseWriter, req *http.Request) { w := &responseTimer{ResponseWriter: WrapResponseWriter(wrapped)} - req = req.WithContext(context.WithValue(req.Context(), &requestTimeContextKey, time.Now())) - lgr := Logger.WithFields(logrus.Fields{ + lgr := ctxlog.FromContext(req.Context()).WithFields(logrus.Fields{ "RequestID": req.Header.Get("X-Request-Id"), "remoteAddr": req.RemoteAddr, "reqForwardedFor": req.Header.Get("X-Forwarded-For"), @@ -37,12 +46,21 @@ func LogRequests(h http.Handler) http.Handler { "reqQuery": req.URL.RawQuery, "reqBytes": req.ContentLength, }) + ctx := req.Context() + ctx = context.WithValue(ctx, &requestTimeContextKey, time.Now()) + ctx = ctxlog.Context(ctx, lgr) + req = req.WithContext(ctx) + logRequest(w, req, lgr) defer logResponse(w, req, lgr) h.ServeHTTP(w, req) }) } +func Logger(req *http.Request) logrus.FieldLogger { + return ctxlog.FromContext(req.Context()) +} + func logRequest(w *responseTimer, req *http.Request, lgr *logrus.Entry) { lgr.Info("request") }