-
Notifications
You must be signed in to change notification settings - Fork 0
/
echo.go
74 lines (64 loc) · 1.54 KB
/
echo.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
package logger
import (
"context"
"fmt"
"github.com/labstack/echo/v4"
"time"
)
var DefaultConfigEcho = ConfigEcho{
SkipperEcho: DefaultSkipperEcho,
}
func EchoMiddleware(config ConfigEcho) echo.MiddlewareFunc {
if config.SkipperEcho == nil {
config.SkipperEcho = DefaultSkipperEcho
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
logger := New(WithFormatter(&JSONFormatter{}))
if config.SkipperEcho(ctx) {
return next(ctx)
}
if config.BeforeFuncEcho != nil {
config.BeforeFuncEcho(ctx)
}
var (
clientIP = ctx.RealIP()
method = ctx.Request().Method
userAgent = ctx.Request().UserAgent()
uri = ctx.Request().RequestURI
errs string
start = time.Now()
isError bool
)
logger.WithFields(map[string]interface{}{
ClientIPField: clientIP,
RequestMethodField: method,
UserAgentField: userAgent,
URIField: uri,
})
ctx.SetRequest(ctx.Request().WithContext(context.WithValue(ctx.Request().Context(), Key, logger)))
ctx.Set(Key, logger)
err := next(ctx)
var (
statusCode = ctx.Response().Status
)
logger.WithField(StatusField, statusCode)
if err != nil {
isError = true
errs = err.Error()
}
if len(errs) > 0 {
logger.WithField(ErrorsField, errs)
}
end := time.Now()
logger.WithField(EndField, end)
msg := fmt.Sprintf("latency: %v", end.Sub(start))
if isError {
logger.Error(msg)
} else {
logger.Info(msg)
}
return err
}
}
}