/
middleware_logger.go
65 lines (54 loc) · 1.82 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
package frontier
import (
"net/http"
"strings"
"time"
"golang.org/x/net/context"
gctx "github.com/goji/context"
"github.com/digitalbitsorg/go/services/frontier/internal/log"
"github.com/digitalbitsorg/go/services/frontier/internal/render"
"github.com/zenazn/goji/web"
"github.com/zenazn/goji/web/middleware"
"github.com/zenazn/goji/web/mutil"
)
// LoggerMiddleware is the middleware that logs http requests and resposnes
// to the logging subsytem of frontier.
func LoggerMiddleware(c *web.C, h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := gctx.FromC(*c)
mw := mutil.WrapWriter(w)
logger := log.WithField("req", middleware.GetReqID(*c))
ctx = log.Set(ctx, logger)
gctx.Set(c, ctx)
logStartOfRequest(ctx, r)
then := time.Now()
h.ServeHTTP(mw, r)
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": r.RemoteAddr,
"host": r.Host,
}).Info("Starting request")
}
func logEndOfRequest(ctx context.Context, r *http.Request, duration time.Duration, mw mutil.WriterProxy, streaming bool) {
log.Ctx(ctx).WithFields(log.F{
"path": r.URL.String(),
"method": r.Method,
"ip": r.RemoteAddr,
"host": r.Host,
"status": mw.Status(),
"bytes": mw.BytesWritten(),
"duration": duration,
"streaming": streaming,
}).Info("Finished request")
}