loghandler.go 5.3 KB

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