add recovery/request log middleware file

This commit is contained in:
MaysWind
2020-10-17 17:48:43 +08:00
parent 0d4493439d
commit 09e98bfc29
2 changed files with 141 additions and 0 deletions
+44
View File
@@ -0,0 +1,44 @@
package middlewares
import (
"time"
"github.com/mayswind/lab/pkg/core"
"github.com/mayswind/lab/pkg/log"
)
func RequestLog(c *core.Context) {
start := time.Now()
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
c.Next()
now := time.Now()
statusCode := c.Writer.Status()
errorCode := 0
userId := "-"
claims := c.GetTokenClaims()
err := c.GetResponseError()
clientIP := c.ClientIP()
method := c.Request.Method
if claims != nil {
userId = claims.Id
}
if err != nil {
errorCode = err.Code()
}
if query != "" {
path = path + "?" + query
}
cost := now.Sub(start).Nanoseconds() / 1e6
log.Requestf(c, "%d %d %s %s %s %s %dms", statusCode, errorCode, userId, clientIP, method, path, cost)
}