loghandler.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. package handler
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/http/httputil"
  9. "time"
  10. "github.com/tal-tech/go-zero/core/iox"
  11. "github.com/tal-tech/go-zero/core/logx"
  12. "github.com/tal-tech/go-zero/core/timex"
  13. "github.com/tal-tech/go-zero/core/utils"
  14. "github.com/tal-tech/go-zero/rest/httpx"
  15. "github.com/tal-tech/go-zero/rest/internal"
  16. )
  17. const slowThreshold = time.Millisecond * 500
  18. type loggedResponseWriter struct {
  19. w http.ResponseWriter
  20. r *http.Request
  21. code int
  22. }
  23. func (w *loggedResponseWriter) Header() http.Header {
  24. return w.w.Header()
  25. }
  26. func (w *loggedResponseWriter) Write(bytes []byte) (int, error) {
  27. return w.w.Write(bytes)
  28. }
  29. func (w *loggedResponseWriter) WriteHeader(code int) {
  30. w.w.WriteHeader(code)
  31. w.code = code
  32. }
  33. func (w *loggedResponseWriter) Flush() {
  34. if flusher, ok := w.w.(http.Flusher); ok {
  35. flusher.Flush()
  36. }
  37. }
  38. // LogHandler returns a middleware that logs http request and response.
  39. func LogHandler(next http.Handler) http.Handler {
  40. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  41. timer := utils.NewElapsedTimer()
  42. logs := new(internal.LogCollector)
  43. lrw := loggedResponseWriter{
  44. w: w,
  45. r: r,
  46. code: http.StatusOK,
  47. }
  48. var dup io.ReadCloser
  49. r.Body, dup = iox.DupReadCloser(r.Body)
  50. next.ServeHTTP(&lrw, r.WithContext(context.WithValue(r.Context(), internal.LogContext, logs)))
  51. r.Body = dup
  52. logBrief(r, lrw.code, timer, logs)
  53. })
  54. }
  55. type detailLoggedResponseWriter struct {
  56. writer *loggedResponseWriter
  57. buf *bytes.Buffer
  58. }
  59. func newDetailLoggedResponseWriter(writer *loggedResponseWriter, buf *bytes.Buffer) *detailLoggedResponseWriter {
  60. return &detailLoggedResponseWriter{
  61. writer: writer,
  62. buf: buf,
  63. }
  64. }
  65. func (w *detailLoggedResponseWriter) Flush() {
  66. w.writer.Flush()
  67. }
  68. func (w *detailLoggedResponseWriter) Header() http.Header {
  69. return w.writer.Header()
  70. }
  71. func (w *detailLoggedResponseWriter) Write(bs []byte) (int, error) {
  72. w.buf.Write(bs)
  73. return w.writer.Write(bs)
  74. }
  75. func (w *detailLoggedResponseWriter) WriteHeader(code int) {
  76. w.writer.WriteHeader(code)
  77. }
  78. // DetailedLogHandler returns a middleware that logs http request and response in details.
  79. func DetailedLogHandler(next http.Handler) http.Handler {
  80. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  81. timer := utils.NewElapsedTimer()
  82. var buf bytes.Buffer
  83. lrw := newDetailLoggedResponseWriter(&loggedResponseWriter{
  84. w: w,
  85. r: r,
  86. code: http.StatusOK,
  87. }, &buf)
  88. var dup io.ReadCloser
  89. r.Body, dup = iox.DupReadCloser(r.Body)
  90. logs := new(internal.LogCollector)
  91. next.ServeHTTP(lrw, r.WithContext(context.WithValue(r.Context(), internal.LogContext, logs)))
  92. r.Body = dup
  93. logDetails(r, lrw, timer, logs)
  94. })
  95. }
  96. func dumpRequest(r *http.Request) string {
  97. reqContent, err := httputil.DumpRequest(r, true)
  98. if err != nil {
  99. return err.Error()
  100. }
  101. return string(reqContent)
  102. }
  103. func logBrief(r *http.Request, code int, timer *utils.ElapsedTimer, logs *internal.LogCollector) {
  104. var buf bytes.Buffer
  105. duration := timer.Duration()
  106. buf.WriteString(fmt.Sprintf("%d - %s - %s - %s - %s",
  107. code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration)))
  108. if duration > slowThreshold {
  109. logx.WithContext(r.Context()).Slowf("[HTTP] %d - %s - %s - %s - slowcall(%s)",
  110. code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration))
  111. }
  112. ok := isOkResponse(code)
  113. if !ok {
  114. buf.WriteString(fmt.Sprintf("\n%s", dumpRequest(r)))
  115. }
  116. body := logs.Flush()
  117. if len(body) > 0 {
  118. buf.WriteString(fmt.Sprintf("\n%s", body))
  119. }
  120. if ok {
  121. logx.WithContext(r.Context()).Info(buf.String())
  122. } else {
  123. logx.WithContext(r.Context()).Error(buf.String())
  124. }
  125. }
  126. func logDetails(r *http.Request, response *detailLoggedResponseWriter, timer *utils.ElapsedTimer,
  127. logs *internal.LogCollector) {
  128. var buf bytes.Buffer
  129. duration := timer.Duration()
  130. buf.WriteString(fmt.Sprintf("%d - %s - %s\n=> %s\n",
  131. response.writer.code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r)))
  132. if duration > slowThreshold {
  133. logx.WithContext(r.Context()).Slowf("[HTTP] %d - %s - slowcall(%s)\n=> %s\n",
  134. response.writer.code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r))
  135. }
  136. body := logs.Flush()
  137. if len(body) > 0 {
  138. buf.WriteString(fmt.Sprintf("%s\n", body))
  139. }
  140. respBuf := response.buf.Bytes()
  141. if len(respBuf) > 0 {
  142. buf.WriteString(fmt.Sprintf("<= %s", respBuf))
  143. }
  144. logx.WithContext(r.Context()).Info(buf.String())
  145. }
  146. func isOkResponse(code int) bool {
  147. // not server error
  148. return code < http.StatusInternalServerError
  149. }