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

64 lines
1.2 KiB

  1. package middleware
  2. import (
  3. "bytes"
  4. "gin-vue-admin/init"
  5. "net/http/httputil"
  6. "strings"
  7. "time"
  8. "github.com/gin-gonic/gin"
  9. )
  10. func Logger() gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. // request time
  13. start := time.Now()
  14. // request path
  15. path := c.Request.URL.Path
  16. logFlag := true
  17. if strings.Contains(path, "swagger") {
  18. logFlag = false
  19. }
  20. // request ip
  21. clientIP := c.ClientIP()
  22. // method
  23. method := c.Request.Method
  24. // copy request content
  25. req, _ := httputil.DumpRequest(c.Request, true)
  26. if logFlag {
  27. init.L.Debug(
  28. "Request:", method, clientIP, path, string(req))
  29. }
  30. // replace writer
  31. cusWriter := &responseBodyWriter{
  32. ResponseWriter: c.Writer,
  33. body: bytes.NewBufferString(""),
  34. }
  35. c.Writer = cusWriter
  36. // handle request
  37. c.Next()
  38. // ending time
  39. end := time.Now()
  40. //execute time
  41. latency := end.Sub(start)
  42. statusCode := c.Writer.Status()
  43. if logFlag {
  44. init.L.Debug(
  45. "Response:",
  46. statusCode,
  47. latency,
  48. cusWriter.body.String())
  49. }
  50. }
  51. }
  52. type responseBodyWriter struct {
  53. gin.ResponseWriter
  54. body *bytes.Buffer
  55. }
  56. func (w responseBodyWriter) Write(b []byte) (int, error) {
  57. w.body.Write(b)
  58. return w.ResponseWriter.Write(b)
  59. }