-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
46 lines (38 loc) · 958 Bytes
/
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"
"fmt"
"net/http"
"time"
"github.com/aleury/service/foundation/web"
"go.uber.org/zap"
)
// Logger creates a middleware that logs the request before and after it is
// processed.
func Logger(log *zap.SugaredLogger) web.Middleware {
return func(handler web.Handler) web.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
v := web.GetValues(ctx)
path := r.URL.Path
if r.URL.RawQuery != "" {
path = fmt.Sprintf("%s?%s", path, r.URL.RawQuery)
}
log.Infow("request started",
"trace_id", v.TraceID,
"method", r.Method,
"path", path,
"remoteAddr", r.RemoteAddr,
)
err := handler(ctx, w, r)
log.Infow("request completed",
"trace_id", v.TraceID,
"method", r.Method,
"path", path,
"remoteAddr", r.RemoteAddr,
"statusCode", fmt.Sprint(v.StatusCode),
"since", time.Since(v.Now).String(),
)
return err
}
}
}