-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.go
48 lines (37 loc) · 1.14 KB
/
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
package zapper
import (
"context"
"net/http"
"go.uber.org/zap"
)
func LogMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// TODO:
// req body
// resp body
// latency 响应时长
newLogger := wrapReqFields(defaultLogger, r)
r.WithContext(context.WithValue(r.Context(), "logger", newLogger))
h.ServeHTTP(w, r)
newLogger.Info("finished handle a request")
})
}
// wrapReqFields 包裹请求携带的字段
func wrapReqFields(logger *zap.Logger, r *http.Request) *zap.Logger {
urlQuery := r.URL.Query()
return logger.With(
// TODO: 找到字段所在报文位置
zap.String("logid", urlQuery.Get("")),
zap.String("caller_ip", r.Header.Get("")),
zap.String("host_ip", r.Host),
zap.String("product", urlQuery.Get("")),
zap.String("module", urlQuery.Get("")),
zap.String("service_id", urlQuery.Get("")),
zap.String("instance_id", urlQuery.Get("")),
zap.String("uri_path", urlQuery.Get("")),
zap.String("tag", urlQuery.Get("")),
zap.String("env", urlQuery.Get("")),
zap.String("sversion", urlQuery.Get("")),
zap.String("stag", urlQuery.Get("")),
)
}