Skip to content

Commit

Permalink
增加响应日志
Browse files Browse the repository at this point in the history
  • Loading branch information
yangguang8131 committed Jun 1, 2021
1 parent 6a35f93 commit f705354
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
2 changes: 1 addition & 1 deletion util/service/server_grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down
15 changes: 14 additions & 1 deletion util/service/server_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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...)
}
Expand Down Expand Up @@ -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)
}

0 comments on commit f705354

Please sign in to comment.