-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
logger.go
57 lines (48 loc) · 1.32 KB
/
logger.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
package echozap
import (
"fmt"
"time"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// ZapLogger is a middleware and zap to provide an "access log" like logging for each request.
func ZapLogger(log *zap.Logger) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
start := time.Now()
err := next(c)
if err != nil {
c.Error(err)
}
req := c.Request()
res := c.Response()
fields := []zapcore.Field{
zap.String("remote_ip", c.RealIP()),
zap.String("latency", time.Since(start).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(err)).Error("Server error", fields...)
case n >= 400:
log.With(zap.Error(err)).Warn("Client error", fields...)
case n >= 300:
log.Info("Redirection", fields...)
default:
log.Info("Success", fields...)
}
return nil
}
}
}