-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger_access.go
88 lines (76 loc) · 1.61 KB
/
logger_access.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
78
79
80
81
82
83
84
85
86
87
88
package middleware
import (
"github.com/bar-counter/gin-correlation-id/gin_correlation_id_snowflake"
"github.com/bridgewwater/gin-api-swagger-temple/internal/zlog/zlog_access"
"github.com/gin-gonic/gin"
"time"
)
// LoggerMiddleware
// just use logger to record
// ip will try X-Forwarded-For, X-Real-Ip
// filter at status code
// less than 400 use Warn
// less than 500 use Error
// other use Warning
// use as
//
// g.Use(middleware.LoggerMiddleware())
func LoggerMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// request router
reqUri := c.Request.RequestURI
if zlog_access.CheckPathIsSkip(reqUri) {
return
}
if zlog_access.CheckPrefixIsSkip(reqUri) {
return
}
// start time
startTime := time.Now()
// to next
c.Next()
// end time
endTime := time.Now()
// latency time
latencyTime := endTime.Sub(startTime)
// request IP
clientIP := c.ClientIP()
// Method
reqMethod := c.Request.Method
// request id
reqId := gin_correlation_id_snowflake.GetCorrelationID(c)
// status code
statusCode := c.Writer.Status()
if statusCode < 400 {
zlog_access.A().Infof(
"=> %15s %13v | %s < %3d rid:%s -> %s",
clientIP,
latencyTime,
reqMethod,
statusCode,
reqId,
reqUri,
)
} else if statusCode < 500 {
zlog_access.A().Warnf(
"=> %15s %13v | %s < %3d rid:%s -> %s",
clientIP,
latencyTime,
reqMethod,
statusCode,
reqId,
reqUri,
)
} else {
zlog_access.A().Errorf(
"=> %15s %13v | %s < %3d rid:%s -> %s",
clientIP,
latencyTime,
reqMethod,
statusCode,
reqId,
reqUri,
)
}
}
}