From f70535430fea014e9903f242b61fac739e999c8c Mon Sep 17 00:00:00 2001 From: yangguang8131 Date: Tue, 1 Jun 2021 16:01:05 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=93=8D=E5=BA=94=E6=97=A5?= =?UTF-8?q?=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- util/service/server_grpc.go | 2 +- util/service/server_http.go | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/util/service/server_grpc.go b/util/service/server_grpc.go index 7c0d729..4772384 100644 --- a/util/service/server_grpc.go +++ b/util/service/server_grpc.go @@ -235,7 +235,7 @@ func monitorServerInterceptor() grpc.UnaryServerInterceptor { st := xtime.NewTimeStat() resp, err = handler(ctx, req) if shouldLogRequest(info.FullMethod) { - xlog.Infow(ctx, "", "func", fun, "req", req, "err", err, "cost", st.Millisecond()) + xlog.Infow(ctx, "", "func", fun, "req", req, "err", err, "cost", st.Millisecond(), "resp", resp) } else { xlog.Infow(ctx, "", "func", fun, "err", err, "cost", st.Millisecond()) } diff --git a/util/service/server_http.go b/util/service/server_http.go index 1ae7d4d..859adc5 100644 --- a/util/service/server_http.go +++ b/util/service/server_http.go @@ -220,6 +220,8 @@ func AccessLog() gin.HandlerFunc { path := c.Request.URL.Path bodyData, _ := c.GetRawData() c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyData)) + blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer} + c.Writer = blw c.Next() @@ -234,7 +236,7 @@ func AccessLog() gin.HandlerFunc { "code", statusCode, } if shouldHttpLogRequest(path) { - keyAndValue = append(keyAndValue, "req", string(bodyData)) + keyAndValue = append(keyAndValue, "req", string(bodyData), "resp", blw.body.String()) } xlog.Infow(ctx, "", keyAndValue...) } @@ -426,3 +428,14 @@ func shouldHttpLogRequest(path string) bool { } return isPrint } + +// gin打印response的方式 +type bodyLogWriter struct { + gin.ResponseWriter + body *bytes.Buffer +} + +func (w bodyLogWriter) Write(b []byte) (int, error) { + w.body.Write(b) + return w.ResponseWriter.Write(b) +}