Files
ginx/middleware/loggerParams.go
T
2024-06-25 18:34:00 +08:00

109 lines
2.6 KiB
Go

package middleware
import (
"bytes"
"encoding/json"
"io"
"log"
"strings"
"github.com/gin-gonic/gin"
)
// 打印请求参数和响应参数
func LoggerParams() gin.HandlerFunc {
return func(ctx *gin.Context) {
buf := &bytes.Buffer{}
tea := io.TeeReader(ctx.Request.Body, buf)
body, err := io.ReadAll(tea)
if err != nil {
log.Panicf("read body err:%+v", err)
}
ctx.Request.Body = io.NopCloser(buf)
// 下面是响应参数缓存
blw := &bodyParamsWriter{
body: bytes.NewBufferString(""),
ResponseWriter: ctx.Writer,
}
ctx.Writer = blw
ctx.Next()
// 判断返回的值是否json
contentType := ctx.Writer.Header().Get("Content-Type")
if !strings.Contains(contentType, "application/json") {
return
}
resp := blw.body.String()
m := map[string]interface{}{
"trace_id": ctx.Keys["trace_id"],
"method": ctx.Request.Method,
"path": ctx.FullPath(),
"client_ip": ctx.ClientIP(),
"body": string(body),
"response": resp,
"request_header": ctx.Request.Header,
"response_code": ctx.Writer.Status(),
}
b, _ := json.Marshal(m)
log.Println(string(b))
}
// return gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
// buf := &bytes.Buffer{}
// tea := io.TeeReader(param.Request.Body, buf)
// body, err := ioutil.ReadAll(tea)
// if err != nil {
// log.Panicf("read body err:%+v", err)
// }
// param.Request.Body = io.NopCloser(buf)
// fmt.Println("ddddd",string(body))
// // 你的自定义格式
// return fmt.Sprintf("[VISIT] trace_id:%s | 参数:%s | IP:%s | 时间:%s | 方法:%s | 路径:%s | 协议:%s | 状态码:%d | 耗时:%s | 代理头:%s | 错误信息:%s \n",
// // trace_id
// param.Keys["trace_id"],
// body,
// //客户端IP
// param.ClientIP,
// //时间格式
// param.TimeStamp.Format("2006-01-02 15:04:05"),
// //http请求方式 get post等
// param.Method,
// //客户端请求的路径
// param.Path,
// //http请求协议版本
// param.Request.Proto,
// //http请求状态码
// param.StatusCode,
// //请求耗时
// param.Latency,
// //http请求代理头
// param.Request.UserAgent(),
// //处理请求错误时设置错误消息
// param.ErrorMessage,
// )
// })
}
type bodyParamsWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
// 真正输出的时候,它会调用这个输出方法
func (w bodyParamsWriter) Write(b []byte) (int, error) {
// b = []byte(`{"code":0}`)
w.body.Write(b)
return w.ResponseWriter.Write(b)
}