forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logging_middleware.go
executable file
·63 lines (55 loc) · 1.49 KB
/
logging_middleware.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
package http
import (
"context"
stdhttp "net/http"
"time"
"github.com/go-chi/chi/middleware"
"github.com/fonero-project/fonero-golang/support/http/mutil"
"github.com/fonero-project/fonero-golang/support/log"
)
// LoggingMiddleware is a middleware that logs requests to the logger.
func LoggingMiddleware(next stdhttp.Handler) stdhttp.Handler {
return stdhttp.HandlerFunc(func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
mw := mutil.WrapWriter(w)
ctx := log.PushContext(r.Context(), func(l *log.Entry) *log.Entry {
return l.WithFields(log.F{
"req": middleware.GetReqID(r.Context()),
})
})
logStartOfRequest(ctx, r)
then := time.Now()
next.ServeHTTP(mw, r)
duration := time.Since(then)
logEndOfRequest(ctx, r, duration, mw)
})
}
// logStartOfRequest emits the logline that reports that an http request is
// beginning processing.
func logStartOfRequest(
ctx context.Context,
r *stdhttp.Request,
) {
log.Ctx(ctx).WithFields(log.F{
"subsys": "http",
"path": r.URL.String(),
"method": r.Method,
"ip": r.RemoteAddr,
"host": r.Host,
}).Info("starting request")
}
// logEndOfRequest emits the logline for the end of the request
func logEndOfRequest(
ctx context.Context,
r *stdhttp.Request,
duration time.Duration,
mw mutil.WriterProxy,
) {
log.Ctx(ctx).WithFields(log.F{
"subsys": "http",
"path": r.URL.String(),
"method": r.Method,
"status": mw.Status(),
"bytes": mw.BytesWritten(),
"duration": duration,
}).Info("finished request")
}