-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
71 lines (56 loc) · 1.53 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
package echotozero
import (
"strconv"
"time"
"github.com/rs/zerolog"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
// MiddleWare logs successful requests to debug, failed req to error, and never skips.
func Middleware(logger *Logger) echo.MiddlewareFunc {
return MiddlewareWithOptions(
logger,
zerolog.DebugLevel,
zerolog.ErrorLevel,
middleware.DefaultSkipper,
)
}
func MiddlewareWithOptions(logger *Logger, successLvl, failLvl zerolog.Level, skipper middleware.Skipper) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// Allows some requests to skip logging
if skipper(c) {
return next(c)
}
start := time.Now()
req := c.Request()
res := c.Response()
// Invokes next middleware or handler
err := next(c)
var evt *zerolog.Event
if err != nil {
// Invokes registered HTTP error handler, if any
c.Error(err)
evt = logger.ZLog.WithLevel(failLvl).Err(err)
} else {
evt = logger.ZLog.WithLevel(successLvl)
}
cl := req.Header.Get(echo.HeaderContentLength)
if cl == "" {
cl = "0"
}
elapsed := time.Since(start)
evt.Dur("elapsed", elapsed)
evt.Str("host", req.Host)
evt.Str("method", req.Method)
evt.Str("remote_ip", c.RealIP())
evt.Str("req_bytes", cl)
evt.Str("res_bytes", strconv.FormatInt(res.Size, 10))
evt.Int("status", res.Status)
evt.Str("uri", req.RequestURI)
evt.Str("user_agent", req.UserAgent())
evt.Msg("HTTP")
return err
}
}
}