Merge branch '16100-mime-types'
[arvados.git] / sdk / go / httpserver / logger.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package httpserver
6
7 import (
8         "context"
9         "net/http"
10         "time"
11
12         "git.arvados.org/arvados.git/sdk/go/ctxlog"
13         "git.arvados.org/arvados.git/sdk/go/stats"
14         "github.com/sirupsen/logrus"
15 )
16
17 type contextKey struct {
18         name string
19 }
20
21 var (
22         requestTimeContextKey = contextKey{"requestTime"}
23 )
24
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))
31         })
32 }
33
34 // LogRequests wraps an http.Handler, logging each request and
35 // response.
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,
44                         "reqHost":         req.Host,
45                         "reqPath":         req.URL.Path[1:],
46                         "reqQuery":        req.URL.RawQuery,
47                         "reqBytes":        req.ContentLength,
48                 })
49                 ctx := req.Context()
50                 ctx = context.WithValue(ctx, &requestTimeContextKey, time.Now())
51                 ctx = ctxlog.Context(ctx, lgr)
52                 req = req.WithContext(ctx)
53
54                 logRequest(w, req, lgr)
55                 defer logResponse(w, req, lgr)
56                 h.ServeHTTP(w, req)
57         })
58 }
59
60 func Logger(req *http.Request) logrus.FieldLogger {
61         return ctxlog.FromContext(req.Context())
62 }
63
64 func logRequest(w *responseTimer, req *http.Request, lgr *logrus.Entry) {
65         lgr.Info("request")
66 }
67
68 func logResponse(w *responseTimer, req *http.Request, lgr *logrus.Entry) {
69         if tStart, ok := req.Context().Value(&requestTimeContextKey).(time.Time); ok {
70                 tDone := time.Now()
71                 writeTime := w.writeTime
72                 if !w.wrote {
73                         // Empty response body. Header was sent when
74                         // handler exited.
75                         writeTime = tDone
76                 }
77                 lgr = lgr.WithFields(logrus.Fields{
78                         "timeTotal":     stats.Duration(tDone.Sub(tStart)),
79                         "timeToStatus":  stats.Duration(writeTime.Sub(tStart)),
80                         "timeWriteBody": stats.Duration(tDone.Sub(writeTime)),
81                 })
82         }
83         respCode := w.WroteStatus()
84         if respCode == 0 {
85                 respCode = http.StatusOK
86         }
87         fields := logrus.Fields{
88                 "respStatusCode": respCode,
89                 "respStatus":     http.StatusText(respCode),
90                 "respBytes":      w.WroteBodyBytes(),
91         }
92         if respCode >= 400 {
93                 fields["respBody"] = string(w.Sniffed())
94         }
95         lgr.WithFields(fields).Info("response")
96 }
97
98 type responseTimer struct {
99         ResponseWriter
100         wrote     bool
101         writeTime time.Time
102 }
103
104 func (rt *responseTimer) CloseNotify() <-chan bool {
105         if cn, ok := rt.ResponseWriter.(http.CloseNotifier); ok {
106                 return cn.CloseNotify()
107         }
108         return nil
109 }
110
111 func (rt *responseTimer) WriteHeader(code int) {
112         if !rt.wrote {
113                 rt.wrote = true
114                 rt.writeTime = time.Now()
115         }
116         rt.ResponseWriter.WriteHeader(code)
117 }
118
119 func (rt *responseTimer) Write(p []byte) (int, error) {
120         if !rt.wrote {
121                 rt.wrote = true
122                 rt.writeTime = time.Now()
123         }
124         return rt.ResponseWriter.Write(p)
125 }