forked from stellar/go
/
middleware_logger.go
67 lines (57 loc) · 2.04 KB
/
middleware_logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package horizon
import (
"context"
"net/http"
"strings"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
chimiddleware "github.com/go-chi/chi/middleware"
"github.com/stellar/go/services/horizon/internal/render"
"github.com/stellar/go/support/log"
)
// LoggerMiddleware is the middleware that logs http requests and resposnes
// to the logging subsytem of horizon.
func LoggerMiddleware(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
mw := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
logger := log.WithField("req", chimiddleware.GetReqID(ctx))
ctx = log.Set(ctx, logger)
logStartOfRequest(ctx, r)
then := time.Now()
h.ServeHTTP(mw, r.WithContext(ctx))
duration := time.Now().Sub(then)
// Checking `Accept` header from user request because if the streaming connection
// is reset before sending the first event no Content-Type header is sent in a response.
acceptHeader := r.Header.Get("Accept")
streaming := strings.Contains(acceptHeader, render.MimeEventStream)
logEndOfRequest(ctx, r, duration, mw, streaming)
}
return http.HandlerFunc(fn)
}
func logStartOfRequest(ctx context.Context, r *http.Request) {
log.Ctx(ctx).WithFields(log.F{
"path": r.URL.String(),
"method": r.Method,
"ip": remoteAddrIP(r),
"ip_port": r.RemoteAddr,
"forwarded_ip": firstXForwardedFor(r),
"host": r.Host,
}).Info("Starting request")
}
func logEndOfRequest(ctx context.Context, r *http.Request, duration time.Duration, mw middleware.WrapResponseWriter, streaming bool) {
log.Ctx(ctx).WithFields(log.F{
"path": r.URL.String(),
"route": chi.RouteContext(r.Context()).RoutePattern(),
"method": r.Method,
"ip": remoteAddrIP(r),
"ip_port": r.RemoteAddr,
"forwarded_ip": firstXForwardedFor(r),
"host": r.Host,
"status": mw.Status(),
"bytes": mw.BytesWritten(),
"duration": duration.Seconds(),
"streaming": streaming,
}).Info("Finished request")
}