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.

57 lines
1.7 KiB

3 years ago
3 years ago
3 years ago
3 years ago
  1. package middleware
  2. import (
  3. "io/ioutil"
  4. "strconv"
  5. "time"
  6. "github.com/flipped-aurora/gin-vue-admin/server/plugin/email/utils"
  7. utils2 "github.com/flipped-aurora/gin-vue-admin/server/utils"
  8. "github.com/flipped-aurora/gin-vue-admin/server/global"
  9. "github.com/flipped-aurora/gin-vue-admin/server/model/system"
  10. "github.com/flipped-aurora/gin-vue-admin/server/service"
  11. "github.com/gin-gonic/gin"
  12. "go.uber.org/zap"
  13. )
  14. var userService = service.ServiceGroupApp.SystemServiceGroup.UserService
  15. func ErrorToEmail() gin.HandlerFunc {
  16. return func(c *gin.Context) {
  17. var username string
  18. claims, _ := utils2.GetClaims(c)
  19. if claims.Username != "" {
  20. username = claims.Username
  21. } else {
  22. id, _ := strconv.Atoi(c.Request.Header.Get("x-user-id"))
  23. err, user := userService.FindUserById(id)
  24. if err != nil {
  25. username = "Unknown"
  26. }
  27. username = user.Username
  28. }
  29. body, _ := ioutil.ReadAll(c.Request.Body)
  30. record := system.SysOperationRecord{
  31. Ip: c.ClientIP(),
  32. Method: c.Request.Method,
  33. Path: c.Request.URL.Path,
  34. Agent: c.Request.UserAgent(),
  35. Body: string(body),
  36. }
  37. now := time.Now()
  38. c.Next()
  39. latency := time.Since(now)
  40. status := c.Writer.Status()
  41. record.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()
  42. str := "接收到的请求为" + record.Body + "\n" + "请求方式为" + record.Method + "\n" + "报错信息如下" + record.ErrorMessage + "\n" + "耗时" + latency.String() + "\n"
  43. if status != 200 {
  44. subject := username + "" + record.Ip + "调用了" + record.Path + "报错了"
  45. if err := utils.ErrorToEmail(subject, str); err != nil {
  46. global.GVA_LOG.Error("ErrorToEmail Failed, err:", zap.Error(err))
  47. }
  48. }
  49. }
  50. }