简单记录下gin中使用中间件记录操作日志

  • 1、直接定义中间件

    go 复制代码
    package middleware
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"github.com/gin-gonic/gin"
    	"go.uber.org/zap"
    	"io"
    	"strconv"
    	"strings"
    )
    
    func LoggerMiddleWare() gin.HandlerFunc {
    	return func(ctx *gin.Context) {
    		//请求方式
    		method := ctx.Request.Method
    		//请求路由
    		reqUrlList := strings.Split(ctx.Request.URL.String(), "?")
    		//状态码
    		statusCode := ctx.Writer.Status()
    		//请求ip
    		clientIP := ctx.ClientIP() 
    		// 获取请求体数据
    		var data map[string]interface{}
    		body, err := io.ReadAll(ctx.Request.Body)
    		// 等于拷贝一份往下传递,否则下接口的方法中拿不到请求体数据
    		ctx.Request.Body = io.NopCloser(bytes.NewBuffer(body))
    		if err != nil {
    			fmt.Println(err, "????")
    		}
    		err = json.Unmarshal(body, &data)
    		// 记录到数据库中,排除登录接口
    		if reqUrlList[0] != "/api/v1/admin/login" {
    			message := ""
    			if method == "GET" {
    				if len(reqUrlList) == 2 && reqUrlList[1] != "" {
    					message = reqUrlList[1]
    				}
    			} else {
    				if utils.MapToJson(data) != "null" {
    					message = utils.MapToJson(data)
    				}
    			}
    			// TODO 插入到数据库中
    		}
    
    		// 打印日志
    		//loggerMap := map[string]interface{} {
    		//	"status_code":statusCode,
    		//	"client_ip": clientIP,
    		//	"req_method":method,
    		//	"req_uri": reqUrl,
    		//}
    		//marshal, _ := json.Marshal(loggerMap)
    		loggerStr := fmt.Sprintf("status_code:%s,client_ip:%s,req_method:%s,req_uri:%s", strconv.Itoa(statusCode), clientIP, method, reqUrlList[0])
    		global.Logger.Info("中间件本次请求", zap.String("http", loggerStr))
    		ctx.Next()
    	}
    }
  • 2、在需要使用的地方直接使用就可以,自动会收集日志到数据库中

相关推荐
_.Switch1 小时前
Python Web 中间件开发与优化指南
开发语言·前端·python·websocket·中间件·架构·django
Chrikk1 小时前
美团中间件C++一面-面经总结
网络·c++·中间件
拾伍廿肆2 小时前
Django 中间件
后端·python·中间件·django
qq_1728055919 小时前
GO GIN & SSE DEMO
网络·golang·gin·sse
SHtop1119 小时前
Gin渲染
gin
weixin_4648381520 小时前
常见中间件漏洞有哪些?
linux·运维·服务器·网络安全·中间件
问道飞鱼1 天前
分布式中间件-分布式协调服务zookeeper
分布式·zookeeper·中间件
Zhong-Xin1 天前
JBOSS中间件漏洞复现
中间件
SHtop111 天前
Gin中间件
中间件·gin
丁总学Java2 天前
中间件:maxwell、canal
中间件·maxwell