14287: Merge branch 'master'
[arvados.git] / sdk / go / httpserver / logger.go
index 569931a3edd732b4fb3d48a09db318622bd08075..f64708454c2b1e12cb5a75906d7d43676629cfb5 100644 (file)
@@ -9,38 +9,58 @@ 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"),
                        "reqMethod":       req.Method,
+                       "reqHost":         req.Host,
                        "reqPath":         req.URL.Path[1:],
+                       "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")
 }