未验证 提交 e6273014 编写于 作者: Mr.奇淼('s avatar Mr.奇淼( 提交者: GitHub

Merge pull request #17 from granty1/master

Modify the logic of log
package servers package servers
import ( import (
"gin-vue-admin/init/qmlog"
"github.com/gin-gonic/gin"
"net/http" "net/http"
"time"
"github.com/gin-gonic/gin"
) )
func ReportFormat(c *gin.Context, success bool, msg string, json gin.H) { func ReportFormat(c *gin.Context, success bool, msg string, json gin.H) {
// 开始时间 // 开始时间
start := time.Now()
path := c.Request.URL.Path
clientIP := c.ClientIP()
method := c.Request.Method
statusCode := c.Writer.Status()
qmlog.QMLog.Infof("| %3d | %13v | %15s | %s %s |%s|",
statusCode,
start,
clientIP,
method, path, gin.H{
"success": success,
"msg": msg,
"data": json,
},
)
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"success": success, "success": success,
"msg": msg, "msg": msg,
......
package middleware package middleware
import ( import (
"bytes"
"gin-vue-admin/init/qmlog" "gin-vue-admin/init/qmlog"
"github.com/gin-gonic/gin" "net/http/httputil"
"strings"
"time" "time"
"github.com/gin-gonic/gin"
) )
func Logger() gin.HandlerFunc { func Logger() gin.HandlerFunc {
log := qmlog.QMLog
return func(c *gin.Context) { return func(c *gin.Context) {
// 开始时间 // request time
start := time.Now() start := time.Now()
// 处理请求 // request path
c.Next()
// 结束时间
end := time.Now()
//执行时间
latency := end.Sub(start)
path := c.Request.URL.Path path := c.Request.URL.Path
logFlag := true
if strings.Contains(path, "swagger") {
logFlag = false
}
// request ip
clientIP := c.ClientIP() clientIP := c.ClientIP()
// method
method := c.Request.Method method := c.Request.Method
// copy request content
req, _ := httputil.DumpRequest(c.Request, true)
if logFlag {
log.Infof(`| %s | %s | %s | %5s | %s\n`,
`Request :`, method, clientIP, path, string(req))
}
// replace writer
cusWriter := &responseBodyWriter{
ResponseWriter: c.Writer,
body: bytes.NewBufferString(""),
}
c.Writer = cusWriter
// handle request
c.Next()
// ending time
end := time.Now()
//execute time
latency := end.Sub(start)
statusCode := c.Writer.Status() statusCode := c.Writer.Status()
buf := make([]byte, 1024) if logFlag {
n, _ := c.Request.Body.Read(buf) log.Infof(`| %s | %3d | %13v | %s \n`,
requestParams := buf[0:n] `Response:`,
qmlog.QMLog.Infof("| %3d | %13v | %15s | %s %s |%s|", statusCode,
statusCode, latency,
latency, cusWriter.body.String())
clientIP, }
method, path, requestParams,
)
} }
} }
type responseBodyWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w responseBodyWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册