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.

55 lines
1.5 KiB

  1. package middleware
  2. import (
  3. "gin-vue-admin/global"
  4. "gin-vue-admin/model"
  5. "gin-vue-admin/model/request"
  6. "gin-vue-admin/service"
  7. "gin-vue-admin/utils"
  8. "github.com/gin-gonic/gin"
  9. "go.uber.org/zap"
  10. "io/ioutil"
  11. "strconv"
  12. "time"
  13. )
  14. func ErrorToEmail() gin.HandlerFunc {
  15. return func(c *gin.Context) {
  16. var username string
  17. if claims, ok := c.Get("claims"); ok {
  18. waitUse := claims.(*request.CustomClaims)
  19. username = waitUse.Username
  20. }else {
  21. id, _ := strconv.Atoi(c.Request.Header.Get("x-user-id"))
  22. err, user := service.FindUserById(id)
  23. if err != nil{
  24. username = "Unknown"
  25. }
  26. username = user.Username
  27. }
  28. body, _ := ioutil.ReadAll(c.Request.Body)
  29. record := model.SysOperationRecord{
  30. Ip: c.ClientIP(),
  31. Method: c.Request.Method,
  32. Path: c.Request.URL.Path,
  33. Agent: c.Request.UserAgent(),
  34. Body: string(body),
  35. }
  36. now := time.Now()
  37. c.Next()
  38. latency := time.Now().Sub(now)
  39. status := c.Writer.Status()
  40. record.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()
  41. str := "接收到的请求为" + record.Body + "\n" + "请求方式为" + record.Method + "\n" + "报错信息如下" + record.ErrorMessage + "\n" + "耗时" + latency.String() + "\n"
  42. if global.GVA_CONFIG.System.ErrorToEmail {
  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.Any("err", err))
  47. }
  48. }
  49. }
  50. }
  51. }