From 1ac6568f67ee303c20f355cf13e8507659a54b13 Mon Sep 17 00:00:00 2001 From: wenjianzhang Date: Mon, 24 May 2021 18:39:53 +0800 Subject: [PATCH] =?UTF-8?q?feat=20=E2=9C=A8=20=E6=97=A5=E5=BF=97=E4=B8=AD?= =?UTF-8?q?=E9=97=B4=E4=BB=B6=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/middleware/logger.go | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/common/middleware/logger.go b/common/middleware/logger.go index 965b3e2f..dacf1f1d 100644 --- a/common/middleware/logger.go +++ b/common/middleware/logger.go @@ -1,7 +1,11 @@ package middleware import ( + "bufio" + "bytes" "encoding/json" + "io" + "io/ioutil" "net/http" "strings" "time" @@ -19,9 +23,24 @@ import ( // LoggerToFile 日志记录到文件 func LoggerToFile() gin.HandlerFunc { return func(c *gin.Context) { + log := api.GetRequestLogger(c) // 开始时间 startTime := time.Now() // 处理请求 + var body string + switch c.Request.Method { + case http.MethodPost, http.MethodPut, http.MethodDelete: + bf := bytes.NewBuffer(nil) + wt := bufio.NewWriter(bf) + _, err := io.Copy(wt, c.Request.Body) + if err != nil { + log.Warnf("copy body error, %s", err.Error()) + err = nil + } + rb, _ := ioutil.ReadAll(bf) + c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(rb)) + body =string(rb) + } c.Next() url := c.Request.RequestURI @@ -34,13 +53,7 @@ func LoggerToFile() gin.HandlerFunc { if c.Request.Method == http.MethodOptions { return } - log := api.GetRequestLogger(c) - - bd, bl := c.Get("body") - var body = "" - if bl { - body = bd.(string) - } + rt, bl := c.Get("result") var result = "" @@ -79,7 +92,7 @@ func LoggerToFile() gin.HandlerFunc { } log.WithFields(logData).Info() - if c.Request.Method != "GET" && c.Request.Method != "OPTIONS" && config.LoggerConfig.EnabledDB { + if c.Request.Method != "OPTIONS" && c.Request.Method != "GET" && config.LoggerConfig.EnabledDB { SetDBOperLog(c, clientIP, statusCode, reqUri, reqMethod, latencyTime, body, result, statusBus) } }