-
Notifications
You must be signed in to change notification settings - Fork 9
/
middleware.go
52 lines (46 loc) · 1.07 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
49
50
51
52
// Package middleware provides echo request and response output log
package middleware
import (
"strconv"
"time"
"github.com/labstack/echo/v4"
"github.com/neko-neko/echo-logrus/v2/log"
)
// Logger returns a middleware that logs HTTP requests.
func Logger() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
req := c.Request()
res := c.Response()
start := time.Now()
var err error
if err = next(c); err != nil {
c.Error(err)
}
stop := time.Now()
id := req.Header.Get(echo.HeaderXRequestID)
if id == "" {
id = res.Header().Get(echo.HeaderXRequestID)
}
reqSize := req.Header.Get(echo.HeaderContentLength)
if reqSize == "" {
reqSize = "0"
}
log.Infof("%s %s [%v] %s %-7s %s %3d %s %s %13v %s %s",
id,
c.RealIP(),
stop.Format(time.RFC3339),
req.Host,
req.Method,
req.RequestURI,
res.Status,
reqSize,
strconv.FormatInt(res.Size, 10),
stop.Sub(start).String(),
req.Referer(),
req.UserAgent(),
)
return err
}
}
}