-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
81 lines (68 loc) · 1.57 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
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
80
81
package eglm
import (
"github.com/GameWith/gwlog"
"github.com/labstack/echo/v4"
"strconv"
"time"
)
// Middleware echo write log middleware
func Middleware(config *Config) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config != nil && config.Skipper != nil {
if config.Skipper(c) {
return next(c)
}
}
fn := DefaultLoggingFunc
if config != nil && config.LoggingFunc != nil {
fn = config.LoggingFunc
}
return loggingHandle(c, next, fn)
}
}
}
func loggingHandle(c echo.Context, next echo.HandlerFunc, fn LoggingFunc) error {
logger, ok := c.Logger().(gwlog.Logger)
if !ok {
err := echo.NewHTTPError(500, "invalid instance type. only gwlog.Logger")
return err
}
req := c.Request()
res := c.Response()
start := time.Now()
var err error
if err = next(c); err != nil {
c.Error(err)
}
stop := time.Now()
p := req.URL.Path
if p == "" {
p = "/"
}
bytesIn := req.Header.Get(echo.HeaderContentLength)
if bytesIn == "" {
bytesIn = "0"
}
// request id
id := req.Header.Get(echo.HeaderXRequestID)
if id == "" {
id = res.Header().Get(echo.HeaderXRequestID)
}
param := &Parameter{
ID: id,
Method: req.Method,
Host: req.Host,
URI: req.RequestURI,
Status: res.Status,
Path: p,
RemoteIP: c.RealIP(),
Referer: req.Referer(),
UserAgent: req.UserAgent(),
Elapsed: int(stop.Sub(start).Milliseconds()),
BytesIn: bytesIn,
BytesOut: strconv.FormatInt(res.Size, 10),
Error: err,
}
return fn(logger, param, c)
}