-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgin.go
74 lines (67 loc) · 1.49 KB
/
gin.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
package logger
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"time"
)
var DefaultConfigGin = ConfigGin{
SkipperGin: DefaultSkipperGin,
}
func GinMiddleware(config ConfigGin) gin.HandlerFunc {
if config.SkipperGin == nil {
config.SkipperGin = DefaultSkipperGin
}
return func(ctx *gin.Context) {
logger := New(WithFormatter(&JSONFormatter{}))
if config.SkipperGin(ctx) {
ctx.Next()
return
}
if config.BeforeFuncGin != nil {
config.BeforeFuncGin(ctx)
}
var (
clientIP = ctx.ClientIP()
method = ctx.Request.Method
userAgent = ctx.Request.UserAgent()
uri = ctx.Request.RequestURI
errs string
start = time.Now()
isError bool
)
logger.WithFields(map[string]interface{}{
ClientIPField: clientIP,
RequestMethodField: method,
UserAgentField: userAgent,
URIField: uri,
})
ctx.Request = ctx.Request.WithContext(context.WithValue(ctx.Request.Context(), Key, logger))
ctx.Set(Key, logger)
ctx.Next()
var (
statusCode = ctx.Writer.Status()
)
logger.WithField(StatusField, statusCode)
if ctx.Errors != nil {
isError = true
bs, err := ctx.Errors.MarshalJSON()
if err == nil {
errs = string(bs)
} else {
errs = ctx.Errors.String()
}
}
if len(errs) > 0 {
logger.WithField(ErrorsField, errs)
}
end := time.Now()
logger.WithField(EndField, end)
msg := fmt.Sprintf("latency: %v", end.Sub(start))
if isError {
logger.Error(msg)
} else {
logger.Info(msg)
}
}
}