operation.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package middleware
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "gin-vue-admin/global"
  6. "gin-vue-admin/model"
  7. "gin-vue-admin/model/request"
  8. "gin-vue-admin/service"
  9. "gin-vue-admin/utils"
  10. "github.com/gin-gonic/gin"
  11. "go.uber.org/zap"
  12. "io/ioutil"
  13. "net/http"
  14. "strconv"
  15. "time"
  16. )
  17. func OperationRecord() gin.HandlerFunc {
  18. return func(c *gin.Context) {
  19. var body []byte
  20. var userId int
  21. if c.Request.Method != http.MethodGet {
  22. var err error
  23. body, err = ioutil.ReadAll(c.Request.Body)
  24. if err != nil {
  25. global.GVA_LOG.Error("read body from request error:", zap.Any("err", err))
  26. } else {
  27. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
  28. }
  29. }
  30. if claims, ok := c.Get("claims"); ok {
  31. waitUse := claims.(*request.CustomClaims)
  32. userId = int(waitUse.ID)
  33. }else {
  34. id, err := strconv.Atoi(c.Request.Header.Get("x-user-id"))
  35. if err != nil {
  36. userId = 0
  37. }
  38. userId = id
  39. }
  40. record := model.SysOperationRecord{
  41. Ip: c.ClientIP(),
  42. Method: c.Request.Method,
  43. Path: c.Request.URL.Path,
  44. Agent: c.Request.UserAgent(),
  45. Body: string(body),
  46. UserID: userId,
  47. }
  48. writer := responseBodyWriter{
  49. ResponseWriter: c.Writer,
  50. body: &bytes.Buffer{},
  51. }
  52. c.Writer = writer
  53. now := time.Now()
  54. c.Next()
  55. latency := time.Now().Sub(now)
  56. record.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()
  57. record.Status = c.Writer.Status()
  58. record.Latency = latency
  59. record.Resp = writer.body.String()
  60. if global.GVA_CONFIG.System.ErrorToEmail {
  61. if record.Status != 200 {
  62. subject := record.Ip+"调用了"+record.Path+"报错了"
  63. body, _ := json.Marshal(record)
  64. if err := utils.ErrorToEmail(subject, string(body)); err != nil{
  65. global.GVA_LOG.Error("ErrorToEmail Failed, err:", zap.Any("err", err))
  66. }
  67. }
  68. }
  69. if err := service.CreateSysOperationRecord(record); err != nil {
  70. global.GVA_LOG.Error("create operation record error:", zap.Any("err", err))
  71. }
  72. }
  73. }
  74. type responseBodyWriter struct {
  75. gin.ResponseWriter
  76. body *bytes.Buffer
  77. }
  78. func (r responseBodyWriter) Write(b []byte) (int, error) {
  79. r.body.Write(b)
  80. return r.ResponseWriter.Write(b)
  81. }