You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

logmiddleware.go 1.6 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package middleware
  2. import (
  3. "github.com/zeromicro/go-zero/core/logx"
  4. "github.com/zeromicro/go-zero/rest/httpx"
  5. "net/http"
  6. "net/http/httputil"
  7. "strings"
  8. )
  9. const (
  10. // ApplicationJson stands for application/json.
  11. ApplicationJson = "application/json"
  12. // ContentType is the header key for Content-Type.
  13. ContentType = "Content-Type"
  14. )
  15. func LogMiddleware(next http.HandlerFunc) http.HandlerFunc {
  16. return func(w http.ResponseWriter, r *http.Request) {
  17. proxy := &responseProxy{w: w}
  18. requestLog(r)
  19. next(proxy, r)
  20. logx.Debug("LogMiddleware response uri:%s jsonResult :%+v", r.RequestURI, string(proxy.body))
  21. }
  22. }
  23. type responseProxy struct {
  24. w http.ResponseWriter
  25. body []byte
  26. }
  27. func (p *responseProxy) Header() http.Header {
  28. return p.w.Header()
  29. }
  30. func (p *responseProxy) Write(data []byte) (int, error) {
  31. p.body = append(p.body, data...)
  32. return p.w.Write(data)
  33. }
  34. func (p *responseProxy) WriteHeader(statusCode int) {
  35. p.w.WriteHeader(statusCode)
  36. }
  37. func requestLog(r *http.Request) {
  38. // 打印所有header
  39. logx.Debug("LogMiddleware request uri:%s header :%+v", r.RequestURI, r.Header)
  40. // json日志
  41. if withJsonBody(r) {
  42. requestDump, err := httputil.DumpRequest(r, true)
  43. logx.Debug("LogMiddleware request uri:%s jsonParams :%+v, err:%+v", r.RequestURI, string(requestDump), err)
  44. } else {
  45. // form表单日志和其他
  46. formParams, err := httpx.GetFormValues(r)
  47. logx.Debug("LogMiddleware request uri:%s formParams :%+v, err:%+v", r.RequestURI, formParams, err)
  48. }
  49. }
  50. func withJsonBody(r *http.Request) bool {
  51. return r.ContentLength > 0 && strings.Contains(r.Header.Get(ContentType), ApplicationJson)
  52. }

PCM is positioned as Software stack over Cloud, aiming to build the standards and ecology of heterogeneous cloud collaboration for JCC in a non intrusive and autonomous peer-to-peer manner.