| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 | package middlewareimport (	"bytes"	"io/ioutil"	"net/http"	"runtime/debug"	"time"	"gitee.com/xuyiping_admin/pkg/logger/zaplog"	"github.com/gin-gonic/gin"	"go.uber.org/zap")type responseBodyWriter struct {	gin.ResponseWriter	body *bytes.Buffer}func (r responseBodyWriter) Write(b []byte) (int, error) {	r.body.Write(b)	return r.ResponseWriter.Write(b)}// GinLogger 接管gin框架默认的日志func GinLogger() gin.HandlerFunc {	return func(c *gin.Context) {		// 获取 response 内容		w := &responseBodyWriter{body: &bytes.Buffer{}, ResponseWriter: c.Writer}		c.Writer = w		var requestBody []byte		if c.Request.Body != nil {			requestBody, _ = ioutil.ReadAll(c.Request.Body)			c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody))		}		start := time.Now()		c.Next()		cost := time.Since(start)		logFields := []zap.Field{			zap.Int("status", c.Writer.Status()),			zap.String("request", c.Request.Method+" "+c.Request.URL.String()),			zap.String("query", c.Request.URL.RawQuery),			zap.String("ip", c.ClientIP()),			zap.String("user-agent", c.Request.UserAgent()),			zap.String("time", cost.String()),			zap.String("Request body", string(requestBody)),			zap.String("Response body", w.body.String()),			zap.String("x-request-id", c.GetHeader("X-Request-ID")),		}		if len(c.Errors) > 0 {			logFields = append(logFields, zap.Any("stack", string(debug.Stack())))			zaplog.Error("Http-Access-Error", logFields...)			c.Abort()		} else {			zaplog.Info("Http-Access-Log", logFields...)		}	}}// GinRecovery recover掉我的项目可能呈现的panicfunc GinRecovery(stack bool) gin.HandlerFunc {	return func(c *gin.Context) {		defer func() {			if err := recover(); err != nil {				body, _ := ioutil.ReadAll(c.Request.Body)				// 获取 panic 发生的位置				var stackTrace []byte				if stack {					// 获取调用栈					stackTrace = debug.Stack()				}				zaplog.Error("panic",					zap.Any("recover", err),					zap.Any("url", c.Request.URL),					zap.Any("stackTrace", string(stackTrace)),					zap.Any("request", string(body)),					zap.String("x-request-id", c.GetHeader("X-Request-ID")),				)				c.AbortWithStatus(http.StatusInternalServerError)				c.Abort()				return			}		}()		c.Next()	}}
 |