kratos 日志请求响应记录

	engine.UseFunc(func(ctx *bm.Context) {
		//var bodyBytes []byte
		body, _ := json.Marshal(ctx.Request.Form)
		//ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
		uuid := tools.GenerateId()
		ctx.Set("uuid", uuid)
		log.Info("请求参数 :url:%v,User-Agent:%v,token:%s,uuid:%v,param:%v", ctx.RoutePath, ctx.Request.Header.Get("User-Agent"), ctx.Request.Header.Get("Authorization"), uuid, string(body))
		ctx.Next()
	})
	engine.UseFunc(func(c *bm.Context) {
		blw := &SesameResponseWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
		c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
		c.Writer = blw
		c.Next()
		uuid, _ := c.Get("uuid")
		log.Info("返回值:url:%v,uuid:%v,data:%v", c.RoutePath, uuid, blw.body.String())
	})


type SesameResponseWriter struct {
	http.ResponseWriter
	// StatusCode is the last int written by the call to WriteHeader(int)
	StatusCode int

	// Output is a string containing the written bytes using the Write([]byte) func.
	Output string

	// header is the internal storage of the http.Header object
	header http.Header

	body *bytes.Buffer
}

func (rw *SesameResponseWriter) Header() http.Header {
	if rw.header == nil {
		rw.header = make(http.Header)
	}
	return rw.header
}

func (rw *SesameResponseWriter) Write(bytes []byte) (int, error) {
	rw.body.Write(bytes)
	return rw.ResponseWriter.Write(bytes)
}

func (rw *SesameResponseWriter) WriteHeader(i int) {
	rw.StatusCode = i
}

  

欢迎大家学习,交流
原文地址:https://www.cnblogs.com/lijintao1025/p/15428942.html