-
-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathzap.go
77 lines (68 loc) · 2.13 KB
/
zap.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
package middleware
import (
"fmt"
"strings"
"time"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/thomaspoignant/go-feature-flag/cmd/relayproxy/config"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// DefaultSkipper is what we use as a default.
// Some endpoints are excluded from the logs to avoid flooding the logs and
// because they are not bringing a lot of value.
func DefaultSkipper(c echo.Context) bool {
skipperURL := []string{"/health", "/info", "/metrics"}
for _, ignoredPath := range skipperURL {
if strings.HasPrefix(ignoredPath, c.Request().URL.String()) {
return true
}
}
return false
}
// DebugSkipper is the skipper used in debug mode, we log everything.
func DebugSkipper(_ echo.Context) bool {
return false
}
// ZapLogger is a middleware and zap to provide an "access log" like logging for each request.
func ZapLogger(log *zap.Logger, cfg *config.Config) echo.MiddlewareFunc {
// select the right skipper
skipper := DefaultSkipper
if cfg != nil && cfg.IsDebugEnabled() {
skipper = DebugSkipper
}
return middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
Skipper: skipper,
LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error {
req := c.Request()
res := c.Response()
fields := []zapcore.Field{
zap.String("remote_ip", c.RealIP()),
zap.String("latency", time.Since(v.StartTime).String()),
zap.String("host", req.Host),
zap.String("request", fmt.Sprintf("%s %s", req.Method, req.RequestURI)),
zap.Int("status", res.Status),
zap.Int64("size", res.Size),
zap.String("user_agent", req.UserAgent()),
}
id := req.Header.Get(echo.HeaderXRequestID)
if id == "" {
id = res.Header().Get(echo.HeaderXRequestID)
}
fields = append(fields, zap.String("request_id", id))
n := res.Status
switch {
case n >= 500:
log.With(zap.Error(v.Error)).Error("Server error", fields...)
case n >= 400:
log.With(zap.Error(v.Error)).Warn("Client error", fields...)
case n >= 300:
log.Debug("Redirection", fields...)
default:
log.Debug("Success", fields...)
}
return nil
},
})
}