-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
logger.go
55 lines (47 loc) · 1.22 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
package main
import (
"github.com/labstack/echo/v4"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"time"
)
// 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()
id := req.Header.Get(echo.HeaderXRequestID)
if id == "" {
id = res.Header().Get(echo.HeaderXRequestID)
}
fields := []zapcore.Field{
zap.String("remote_ip", c.RealIP()),
zap.String("time", time.Since(start).String()),
zap.String("request_id", id),
zap.String("host", req.Host),
zap.String("method", req.Method),
zap.String("uri", req.RequestURI),
zap.Int("status", res.Status),
zap.String("size", res.Header().Get("Content-Length")),
}
n := res.Status
switch {
case n >= 500:
log.Error("Server error", fields...)
case n >= 400:
log.Warn("Client error", fields...)
case n >= 300:
log.Info("Redirection", fields...)
default:
log.Info("Success", fields...)
}
return nil
}
}
}