From a20af0ae5e96b5e6843908f9af88e17ca0936484 Mon Sep 17 00:00:00 2001 From: Granty1 Date: Mon, 30 Dec 2019 19:21:40 +0800 Subject: [PATCH] Refine the logic of log middleware, add response body. --- QMPlusServer/middleware/logger.go | 56 +++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 17 deletions(-) diff --git a/QMPlusServer/middleware/logger.go b/QMPlusServer/middleware/logger.go index 63ebde02..508ec472 100644 --- a/QMPlusServer/middleware/logger.go +++ b/QMPlusServer/middleware/logger.go @@ -1,34 +1,56 @@ package middleware import ( - "gin-vue-admin/init/qmlog" - "github.com/gin-gonic/gin" + "bytes" + "net/http/httputil" "time" + + "github.com/gin-gonic/gin" + "qiniupkg.com/x/log.v7" ) func Logger() gin.HandlerFunc { return func(c *gin.Context) { - // 开始时间 + // request time start := time.Now() - // 处理请求 - c.Next() - // 结束时间 - end := time.Now() - //执行时间 - latency := end.Sub(start) - + // request path path := c.Request.URL.Path + // request ip clientIP := c.ClientIP() + // method method := c.Request.Method + // copy request content + req, _ := httputil.DumpRequest(c.Request, true) + 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() - buf := make([]byte, 1024) - n, _ := c.Request.Body.Read(buf) - requestParams := buf[0:n] - qmlog.QMLog.Infof("| %3d | %13v | %15s | %s %s |%s|", + + log.Infof(`| %s | %3d | %13v | %s \n`, + `Response:`, statusCode, latency, - clientIP, - method, path, requestParams, - ) + cusWriter.body.String()) } } + +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) +} -- GitLab