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 // HandlerWithContext returns an http.Handler that changes the request
26 // context to ctx (replacing http.Server's default
27 // context.Background()), then calls next.
28 func HandlerWithContext(ctx context.Context, next http.Handler) http.Handler {
29 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
30 next.ServeHTTP(w, r.WithContext(ctx))
34 // LogRequests wraps an http.Handler, logging each request and
36 func LogRequests(h http.Handler) http.Handler {
37 return http.HandlerFunc(func(wrapped http.ResponseWriter, req *http.Request) {
38 w := &responseTimer{ResponseWriter: WrapResponseWriter(wrapped)}
39 lgr := ctxlog.FromContext(req.Context()).WithFields(logrus.Fields{
40 "RequestID": req.Header.Get("X-Request-Id"),
41 "remoteAddr": req.RemoteAddr,
42 "reqForwardedFor": req.Header.Get("X-Forwarded-For"),
43 "reqMethod": req.Method,
45 "reqPath": req.URL.Path[1:],
46 "reqQuery": req.URL.RawQuery,
47 "reqBytes": req.ContentLength,
50 ctx = context.WithValue(ctx, &requestTimeContextKey, time.Now())
51 ctx = ctxlog.Context(ctx, lgr)
52 req = req.WithContext(ctx)
54 logRequest(w, req, lgr)
55 defer logResponse(w, req, lgr)
56 h.ServeHTTP(rewrapResponseWriter(w, wrapped), req)
60 // Rewrap w to restore additional interfaces provided by wrapped.
61 func rewrapResponseWriter(w http.ResponseWriter, wrapped http.ResponseWriter) http.ResponseWriter {
62 if hijacker, ok := wrapped.(http.Hijacker); ok {
71 func Logger(req *http.Request) logrus.FieldLogger {
72 return ctxlog.FromContext(req.Context())
75 func logRequest(w *responseTimer, req *http.Request, lgr *logrus.Entry) {
79 func logResponse(w *responseTimer, req *http.Request, lgr *logrus.Entry) {
80 if tStart, ok := req.Context().Value(&requestTimeContextKey).(time.Time); ok {
82 writeTime := w.writeTime
84 // Empty response body. Header was sent when
88 lgr = lgr.WithFields(logrus.Fields{
89 "timeTotal": stats.Duration(tDone.Sub(tStart)),
90 "timeToStatus": stats.Duration(writeTime.Sub(tStart)),
91 "timeWriteBody": stats.Duration(tDone.Sub(writeTime)),
94 respCode := w.WroteStatus()
96 respCode = http.StatusOK
98 fields := logrus.Fields{
99 "respStatusCode": respCode,
100 "respStatus": http.StatusText(respCode),
101 "respBytes": w.WroteBodyBytes(),
104 fields["respBody"] = string(w.Sniffed())
106 lgr.WithFields(fields).Info("response")
109 type responseTimer struct {
115 func (rt *responseTimer) CloseNotify() <-chan bool {
116 if cn, ok := rt.ResponseWriter.(http.CloseNotifier); ok {
117 return cn.CloseNotify()
122 func (rt *responseTimer) WriteHeader(code int) {
125 rt.writeTime = time.Now()
127 rt.ResponseWriter.WriteHeader(code)
130 func (rt *responseTimer) Write(p []byte) (int, error) {
133 rt.writeTime = time.Now()
135 return rt.ResponseWriter.Write(p)