generated from Improwised/golang-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_logger.go
53 lines (49 loc) · 1.52 KB
/
http_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
package middleware
import (
"github.com/Improwised/golang-api/utils"
"github.com/gofiber/fiber/v2"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var (
zapCoreField []zapcore.Field
// Add path that needs to excluded from logging
ignorePathList = []string{
"/docs",
"/assets/redoc.css",
"/assets/redoc.standalone.js",
"/assets/swagger.json",
"/favicon.ico",
}
)
// Handler will log each request
func Handler(logger *zap.Logger) fiber.Handler {
return func(ctx *fiber.Ctx) error {
err := ctx.Next()
if err != nil {
return err
}
exits, _ := utils.InArray(ctx.Path(), ignorePathList)
if !exits {
zapCoreField = []zapcore.Field{
zap.String("host", ctx.Hostname()),
zap.String("method", string(ctx.Request().Header.Method())),
zap.String("uri", ctx.BaseURL()),
zap.String("protocol", ctx.Protocol()),
zap.String("username", string(ctx.Request().URI().Username())),
zap.String("requestHeaders", string(ctx.Request().Header.Header())),
zap.String("responseHeaders", string(ctx.Response().Header.Header())),
zap.String("request", string(ctx.Request().Body())),
zap.String("response", ctx.Response().String()),
zap.Int("status", ctx.Response().Header.StatusCode()),
zap.Int("size", ctx.Response().Header.ContentLength()),
}
if ctx.Response().Header.StatusCode() >= 100 && ctx.Response().Header.StatusCode() <= 399 {
logger.Debug("Handled successful request", zapCoreField...)
} else {
logger.Error("handled error request", zapCoreField...)
}
}
return nil
}
}