/
logger.go
46 lines (34 loc) · 1.23 KB
/
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
package mid
import (
"context"
"net/http"
"time"
"github.com/ardanlabs/bets/foundation/web"
"go.uber.org/zap"
)
// Logger writes some information about the request to the logs in the
// format: TraceID : (200) GET /foo -> IP ADDR (latency)
func Logger(log *zap.SugaredLogger) web.Middleware {
// This is the actual middleware function to be executed.
m := func(handler web.Handler) web.Handler {
// Create the handler that will be attached in the middleware chain.
h := func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
// If the context is missing this value, request the service
// to be shutdown gracefully.
v, err := web.GetValues(ctx)
if err != nil {
return web.NewShutdownError("web value missing from context")
}
log.Infow("request started", "traceid", v.TraceID, "method", r.Method, "path", r.URL.Path,
"remoteaddr", r.RemoteAddr)
// Call the next handler.
err = handler(ctx, w, r)
log.Infow("request completed", "traceid", v.TraceID, "method", r.Method, "path", r.URL.Path,
"remoteaddr", r.RemoteAddr, "statuscode", v.StatusCode, "since", time.Since(v.Now))
// Return the error so it can be handled further up the chain.
return err
}
return h
}
return m
}