loghandler.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. func LogHandler(next http.Handler) http.Handler {
  39. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  40. timer := utils.NewElapsedTimer()
  41. logs := new(internal.LogCollector)
  42. lrw := LoggedResponseWriter{
  43. w: w,
  44. r: r,
  45. code: http.StatusOK,
  46. }
  47. var dup io.ReadCloser
  48. r.Body, dup = iox.DupReadCloser(r.Body)
  49. next.ServeHTTP(&lrw, r.WithContext(context.WithValue(r.Context(), internal.LogContext, logs)))
  50. r.Body = dup
  51. logBrief(r, lrw.code, timer, logs)
  52. })
  53. }
  54. type DetailLoggedResponseWriter struct {
  55. writer *LoggedResponseWriter
  56. buf *bytes.Buffer
  57. }
  58. func newDetailLoggedResponseWriter(writer *LoggedResponseWriter, buf *bytes.Buffer) *DetailLoggedResponseWriter {
  59. return &DetailLoggedResponseWriter{
  60. writer: writer,
  61. buf: buf,
  62. }
  63. }
  64. func (w *DetailLoggedResponseWriter) Flush() {
  65. w.writer.Flush()
  66. }
  67. func (w *DetailLoggedResponseWriter) Header() http.Header {
  68. return w.writer.Header()
  69. }
  70. func (w *DetailLoggedResponseWriter) Write(bs []byte) (int, error) {
  71. w.buf.Write(bs)
  72. return w.writer.Write(bs)
  73. }
  74. func (w *DetailLoggedResponseWriter) WriteHeader(code int) {
  75. w.writer.WriteHeader(code)
  76. }
  77. func DetailedLogHandler(next http.Handler) http.Handler {
  78. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  79. timer := utils.NewElapsedTimer()
  80. var buf bytes.Buffer
  81. lrw := newDetailLoggedResponseWriter(&LoggedResponseWriter{
  82. w: w,
  83. r: r,
  84. code: http.StatusOK,
  85. }, &buf)
  86. var dup io.ReadCloser
  87. r.Body, dup = iox.DupReadCloser(r.Body)
  88. logs := new(internal.LogCollector)
  89. next.ServeHTTP(lrw, r.WithContext(context.WithValue(r.Context(), internal.LogContext, logs)))
  90. r.Body = dup
  91. logDetails(r, lrw, timer, logs)
  92. })
  93. }
  94. func dumpRequest(r *http.Request) string {
  95. reqContent, err := httputil.DumpRequest(r, true)
  96. if err != nil {
  97. return err.Error()
  98. }
  99. return string(reqContent)
  100. }
  101. func logBrief(r *http.Request, code int, timer *utils.ElapsedTimer, logs *internal.LogCollector) {
  102. var buf bytes.Buffer
  103. duration := timer.Duration()
  104. buf.WriteString(fmt.Sprintf("%d - %s - %s - %s - %s",
  105. code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration)))
  106. if duration > slowThreshold {
  107. logx.WithContext(r.Context()).Slowf("[HTTP] %d - %s - %s - %s - slowcall(%s)",
  108. code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration))
  109. }
  110. ok := isOkResponse(code)
  111. if !ok {
  112. buf.WriteString(fmt.Sprintf("\n%s", dumpRequest(r)))
  113. }
  114. body := logs.Flush()
  115. if len(body) > 0 {
  116. buf.WriteString(fmt.Sprintf("\n%s", body))
  117. }
  118. if ok {
  119. logx.WithContext(r.Context()).Info(buf.String())
  120. } else {
  121. logx.WithContext(r.Context()).Error(buf.String())
  122. }
  123. }
  124. func logDetails(r *http.Request, response *DetailLoggedResponseWriter, timer *utils.ElapsedTimer,
  125. logs *internal.LogCollector) {
  126. var buf bytes.Buffer
  127. duration := timer.Duration()
  128. buf.WriteString(fmt.Sprintf("%d - %s - %s\n=> %s\n",
  129. response.writer.code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r)))
  130. if duration > slowThreshold {
  131. logx.WithContext(r.Context()).Slowf("[HTTP] %d - %s - slowcall(%s)\n=> %s\n",
  132. response.writer.code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r))
  133. }
  134. body := logs.Flush()
  135. if len(body) > 0 {
  136. buf.WriteString(fmt.Sprintf("%s\n", body))
  137. }
  138. respBuf := response.buf.Bytes()
  139. if len(respBuf) > 0 {
  140. buf.WriteString(fmt.Sprintf("<= %s", respBuf))
  141. }
  142. logx.WithContext(r.Context()).Info(buf.String())
  143. }
  144. func isOkResponse(code int) bool {
  145. // not server error
  146. return code < http.StatusInternalServerError
  147. }