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. } else {
  99. return string(reqContent)
  100. }
  101. }
  102. func logBrief(r *http.Request, code int, timer *utils.ElapsedTimer, logs *internal.LogCollector) {
  103. var buf bytes.Buffer
  104. duration := timer.Duration()
  105. buf.WriteString(fmt.Sprintf("%d - %s - %s - %s - %s",
  106. code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration)))
  107. if duration > slowThreshold {
  108. logx.WithContext(r.Context()).Slowf("[HTTP] %d - %s - %s - %s - slowcall(%s)",
  109. code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration))
  110. }
  111. ok := isOkResponse(code)
  112. if !ok {
  113. buf.WriteString(fmt.Sprintf("\n%s", dumpRequest(r)))
  114. }
  115. body := logs.Flush()
  116. if len(body) > 0 {
  117. buf.WriteString(fmt.Sprintf("\n%s", body))
  118. }
  119. if ok {
  120. logx.WithContext(r.Context()).Info(buf.String())
  121. } else {
  122. logx.WithContext(r.Context()).Error(buf.String())
  123. }
  124. }
  125. func logDetails(r *http.Request, response *DetailLoggedResponseWriter, timer *utils.ElapsedTimer,
  126. logs *internal.LogCollector) {
  127. var buf bytes.Buffer
  128. duration := timer.Duration()
  129. buf.WriteString(fmt.Sprintf("%d - %s - %s\n=> %s\n",
  130. response.writer.code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r)))
  131. if duration > slowThreshold {
  132. logx.WithContext(r.Context()).Slowf("[HTTP] %d - %s - slowcall(%s)\n=> %s\n",
  133. response.writer.code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r))
  134. }
  135. body := logs.Flush()
  136. if len(body) > 0 {
  137. buf.WriteString(fmt.Sprintf("%s\n", body))
  138. }
  139. respBuf := response.buf.Bytes()
  140. if len(respBuf) > 0 {
  141. buf.WriteString(fmt.Sprintf("<= %s", respBuf))
  142. }
  143. logx.WithContext(r.Context()).Info(buf.String())
  144. }
  145. func isOkResponse(code int) bool {
  146. // not server error
  147. return code < http.StatusInternalServerError
  148. }