gitee.com/woood2/luca@v1.0.4/cmd/backend/internal/middleware/oplog.go (about)

     1  package middleware
     2  
     3  import (
     4  	"bytes"
     5  	"gitee.com/woood2/luca/internal/layer"
     6  	"gitee.com/woood2/luca/internal/trace"
     7  	"github.com/gin-gonic/gin"
     8  	"go.uber.org/zap"
     9  	"io/ioutil"
    10  	"time"
    11  )
    12  
    13  func Oplog(res string, logger *zap.Logger) gin.HandlerFunc {
    14  	return func(c *gin.Context) {
    15  		begin := time.Now()
    16  		bd := getBody(c)
    17  
    18  		c.Next()
    19  
    20  		traceID := trace.GinID(c)
    21  		rst := getOptResult(c)
    22  		uid := getUid(c)
    23  		uname := getUname(c)
    24  
    25  		logger.Info("opt happen",
    26  			zap.String("opt", res),
    27  			zap.Duration("took", time.Since(begin)),
    28  			zap.String("rst", rst),
    29  			zap.Int("uid", uid),
    30  			zap.String("uname", uname),
    31  			zap.String("ip", c.ClientIP()),
    32  			zap.String("traceID", traceID),
    33  			zap.String("method", c.Request.Method),
    34  			zap.String("requestURI", c.Request.RequestURI),
    35  			zap.String("token", c.Request.Header.Get("Token")),
    36  			zap.String("body", bd),
    37  		)
    38  	}
    39  }
    40  
    41  func getBody(c *gin.Context) string {
    42  	var bodyBytes []byte
    43  	if c.Request.Body != nil {
    44  		bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
    45  		c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) // 返回body中的原值
    46  	}
    47  	return string(bodyBytes)
    48  }
    49  
    50  func getOptResult(c *gin.Context) string {
    51  	if v, exists := c.Get(layer.GinCtxKeyOptResult); exists {
    52  		if rst, ok := v.(string); ok {
    53  			return rst
    54  		}
    55  	}
    56  	return layer.OptResultFail
    57  }
    58  
    59  func getUid(c *gin.Context) int {
    60  	if v, exists := c.Get(GinCtxKeyUid); exists {
    61  		if uid, ok := v.(int); ok {
    62  			return uid
    63  		}
    64  	}
    65  	return 0
    66  }
    67  
    68  func getUname(c *gin.Context) string {
    69  	if v, exists := c.Get(GinCtxKeyUname); exists {
    70  		if uname, ok := v.(string); ok {
    71  			return uname
    72  		}
    73  	}
    74  	return ""
    75  }