-
Notifications
You must be signed in to change notification settings - Fork 0
/
logging.go
63 lines (50 loc) · 1.18 KB
/
logging.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 middleware
import (
"context"
"net/http"
"time"
"github.com/efritz/glock"
"github.com/efritz/response"
"github.com/go-nacelle/nacelle"
"github.com/go-nacelle/chevron"
)
type LoggingMiddleware struct {
clock glock.Clock
}
func NewLogging(configs ...LoggingConfigFunc) chevron.Middleware {
m := &LoggingMiddleware{
clock: glock.NewRealClock(),
}
for _, f := range configs {
f(m)
}
return m
}
func (m *LoggingMiddleware) Convert(f chevron.Handler) (chevron.Handler, error) {
handler := func(ctx context.Context, req *http.Request, logger nacelle.Logger) response.Response {
logger = logger.WithFields(nacelle.LogFields{
"method": req.Method,
"request_uri": req.RequestURI,
"client": req.RemoteAddr,
"request_host": req.Host,
"user_agent": req.UserAgent(),
})
logger.Info(
"Handling HTTP request %s %s",
req.Method,
req.RequestURI,
)
start := m.clock.Now()
resp := f(ctx, req, logger)
duration := int(m.clock.Now().Sub(start) / time.Millisecond)
logger.Info(
"Handled HTTP request %s %s -> %d in %dms",
req.Method,
req.RequestURI,
resp.StatusCode(),
duration,
)
return resp
}
return handler, nil
}