-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger_middleware.go
79 lines (69 loc) · 1.41 KB
/
logger_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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package echo
import (
"strconv"
"time"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
)
var loggerMiddlewareFieldNames = []string{
"id",
"real_ip",
"method",
"status",
"proto",
"host",
"uri",
"path",
"referer",
"agent",
"latency",
"bytes_in",
"bytes_out",
}
// LoggerMiddleware returns a middleware that logs HTTP requests.
func LoggerMiddleware(log *zap.Logger) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
var (
req = c.Request()
res = c.Response()
start = time.Now()
err = next(c)
stop = time.Now()
)
id := req.Header.Get(echo.HeaderXRequestID)
if id == "" {
id = res.Header().Get(echo.HeaderXRequestID)
}
p := req.URL.Path
if p == "" {
p = "/"
}
items := []string{
id,
c.RealIP(),
req.Method,
strconv.Itoa(res.Status),
req.Proto,
req.Host,
req.RequestURI,
p,
req.Referer(),
req.UserAgent(),
stop.Sub(start).String(),
req.Header.Get(echo.HeaderContentLength),
strconv.FormatInt(res.Size, 10),
}
fields := make([]zap.Field, 0, len(items))
for i := 0; i < len(loggerMiddlewareFieldNames); i++ {
if items[i] != "" {
fields = append(fields,
zap.String(loggerMiddlewareFieldNames[i], items[i]))
}
}
fields = append(fields, zap.Error(err))
log.Info("new request", fields...)
return err
}
}
}