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.

65 lines
1.3 KiB

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