Commit
This commit is contained in:
54
middleware/request_log.go
Normal file
54
middleware/request_log.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"nCovTrack-Backend/utils"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func RequestLog() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var logParams []interface{}
|
||||
|
||||
// All requests' log;
|
||||
logParams = append(logParams,
|
||||
"uri", c.Request.RequestURI,
|
||||
"mothod", c.Request.Method,
|
||||
)
|
||||
startTime := time.Now()
|
||||
|
||||
c.Next()
|
||||
|
||||
cost := time.Since(startTime)
|
||||
logParams = append(logParams, "cost", cost.String())
|
||||
|
||||
// Log while request is allright;
|
||||
if c.Writer.Status() == http.StatusOK && cost.Milliseconds() < 800 {
|
||||
utils.RequestLogInfo(logParams...)
|
||||
return
|
||||
}
|
||||
|
||||
// Log while request cost an unexpected time;
|
||||
if cost >= 800 {
|
||||
logParams = append(logParams,
|
||||
"status", c.Writer.Status(),
|
||||
"query", c.Request.URL.Query(),
|
||||
"header", c.Request.Header,
|
||||
"body", c.Request.Body,
|
||||
"ip", c.ClientIP(),
|
||||
)
|
||||
utils.RequestLogWarn(logParams...)
|
||||
return
|
||||
}
|
||||
|
||||
// Log while response occurred some error;
|
||||
if c.Writer.Status() != http.StatusOK {
|
||||
logParams = append(logParams,
|
||||
"error", c.Errors.ByType(gin.ErrorTypePrivate).String(),
|
||||
)
|
||||
utils.RequestLogError(logParams...)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user