1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
12 "git.arvados.org/arvados.git/sdk/go/ctxlog"
13 "git.arvados.org/arvados.git/sdk/go/stats"
14 "github.com/sirupsen/logrus"
17 type contextKey struct {
22 requestTimeContextKey = contextKey{"requestTime"}
25 // HandlerWithDeadline cancels the request context if the request
26 // takes longer than the specified timeout.
27 func HandlerWithDeadline(timeout time.Duration, next http.Handler) http.Handler {
28 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
29 ctx, cancel := context.WithDeadline(r.Context(), time.Now().Add(timeout))
31 next.ServeHTTP(w, r.WithContext(ctx))
35 // LogRequests wraps an http.Handler, logging each request and
37 func LogRequests(h http.Handler) http.Handler {
38 return http.HandlerFunc(func(wrapped http.ResponseWriter, req *http.Request) {
39 w := &responseTimer{ResponseWriter: WrapResponseWriter(wrapped)}
40 lgr := ctxlog.FromContext(req.Context()).WithFields(logrus.Fields{
41 "RequestID": req.Header.Get("X-Request-Id"),
42 "remoteAddr": req.RemoteAddr,
43 "reqForwardedFor": req.Header.Get("X-Forwarded-For"),
44 "reqMethod": req.Method,
46 "reqPath": req.URL.Path[1:],
47 "reqQuery": req.URL.RawQuery,
48 "reqBytes": req.ContentLength,
51 ctx = context.WithValue(ctx, &requestTimeContextKey, time.Now())
52 ctx = ctxlog.Context(ctx, lgr)
53 req = req.WithContext(ctx)
55 logRequest(w, req, lgr)
56 defer logResponse(w, req, lgr)
57 h.ServeHTTP(rewrapResponseWriter(w, wrapped), req)
61 // Rewrap w to restore additional interfaces provided by wrapped.
62 func rewrapResponseWriter(w http.ResponseWriter, wrapped http.ResponseWriter) http.ResponseWriter {
63 if hijacker, ok := wrapped.(http.Hijacker); ok {
72 func Logger(req *http.Request) logrus.FieldLogger {
73 return ctxlog.FromContext(req.Context())
76 func logRequest(w *responseTimer, req *http.Request, lgr *logrus.Entry) {
80 func logResponse(w *responseTimer, req *http.Request, lgr *logrus.Entry) {
81 if tStart, ok := req.Context().Value(&requestTimeContextKey).(time.Time); ok {
83 writeTime := w.writeTime
85 // Empty response body. Header was sent when
89 lgr = lgr.WithFields(logrus.Fields{
90 "timeTotal": stats.Duration(tDone.Sub(tStart)),
91 "timeToStatus": stats.Duration(writeTime.Sub(tStart)),
92 "timeWriteBody": stats.Duration(tDone.Sub(writeTime)),
95 respCode := w.WroteStatus()
97 respCode = http.StatusOK
99 fields := logrus.Fields{
100 "respStatusCode": respCode,
101 "respStatus": http.StatusText(respCode),
102 "respBytes": w.WroteBodyBytes(),
105 fields["respBody"] = string(w.Sniffed())
107 lgr.WithFields(fields).Info("response")
110 type responseTimer struct {
116 func (rt *responseTimer) CloseNotify() <-chan bool {
117 if cn, ok := rt.ResponseWriter.(http.CloseNotifier); ok {
118 return cn.CloseNotify()
123 func (rt *responseTimer) WriteHeader(code int) {
126 rt.writeTime = time.Now()
128 rt.ResponseWriter.WriteHeader(code)
131 func (rt *responseTimer) Write(p []byte) (int, error) {
134 rt.writeTime = time.Now()
136 return rt.ResponseWriter.Write(p)