7931: Merge branch 'master' into 7931-replicas-by-volume
[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.curoverse.com/arvados.git/sdk/go/stats"
13         "github.com/Sirupsen/logrus"
14 )
15
16 type contextKey struct {
17         name string
18 }
19
20 var requestTimeContextKey = contextKey{"requestTime"}
21
22 var Logger logrus.FieldLogger = logrus.StandardLogger()
23
24 // LogRequests wraps an http.Handler, logging each request and
25 // response via logrus.
26 func LogRequests(h http.Handler) http.Handler {
27         return http.HandlerFunc(func(wrapped http.ResponseWriter, req *http.Request) {
28                 w := &responseTimer{ResponseWriter: WrapResponseWriter(wrapped)}
29                 req = req.WithContext(context.WithValue(req.Context(), &requestTimeContextKey, time.Now()))
30                 lgr := Logger.WithFields(logrus.Fields{
31                         "RequestID":       req.Header.Get("X-Request-Id"),
32                         "remoteAddr":      req.RemoteAddr,
33                         "reqForwardedFor": req.Header.Get("X-Forwarded-For"),
34                         "reqMethod":       req.Method,
35                         "reqPath":         req.URL.Path[1:],
36                         "reqBytes":        req.ContentLength,
37                 })
38                 logRequest(w, req, lgr)
39                 defer logResponse(w, req, lgr)
40                 h.ServeHTTP(w, req)
41         })
42 }
43
44 func logRequest(w *responseTimer, req *http.Request, lgr *logrus.Entry) {
45         lgr.Info("request")
46 }
47
48 func logResponse(w *responseTimer, req *http.Request, lgr *logrus.Entry) {
49         if tStart, ok := req.Context().Value(&requestTimeContextKey).(time.Time); ok {
50                 tDone := time.Now()
51                 lgr = lgr.WithFields(logrus.Fields{
52                         "timeTotal":     stats.Duration(tDone.Sub(tStart)),
53                         "timeToStatus":  stats.Duration(w.writeTime.Sub(tStart)),
54                         "timeWriteBody": stats.Duration(tDone.Sub(w.writeTime)),
55                 })
56         }
57         respCode := w.WroteStatus()
58         if respCode == 0 {
59                 respCode = http.StatusOK
60         }
61         lgr.WithFields(logrus.Fields{
62                 "respStatusCode": respCode,
63                 "respStatus":     http.StatusText(respCode),
64                 "respBytes":      w.WroteBodyBytes(),
65         }).Info("response")
66 }
67
68 type responseTimer struct {
69         ResponseWriter
70         wrote     bool
71         writeTime time.Time
72 }
73
74 func (rt *responseTimer) CloseNotify() <-chan bool {
75         if cn, ok := rt.ResponseWriter.(http.CloseNotifier); ok {
76                 return cn.CloseNotify()
77         }
78         return nil
79 }
80
81 func (rt *responseTimer) WriteHeader(code int) {
82         if !rt.wrote {
83                 rt.wrote = true
84                 rt.writeTime = time.Now()
85         }
86         rt.ResponseWriter.WriteHeader(code)
87 }
88
89 func (rt *responseTimer) Write(p []byte) (int, error) {
90         if !rt.wrote {
91                 rt.wrote = true
92                 rt.writeTime = time.Now()
93         }
94         return rt.ResponseWriter.Write(p)
95 }