55 lines
1.1 KiB
Go
55 lines
1.1 KiB
Go
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.Milliseconds() >= 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...)
|
|
}
|
|
}
|
|
}
|