operation.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package middleware
  2. import (
  3. "bytes"
  4. "gin-vue-admin/global"
  5. "gin-vue-admin/model"
  6. "gin-vue-admin/service"
  7. "github.com/gin-gonic/gin"
  8. "io/ioutil"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. )
  13. var body []byte
  14. func RecordRequestBody() gin.HandlerFunc {
  15. return func(c *gin.Context) {
  16. if c.Request.Method != http.MethodGet {
  17. var err error
  18. body, err = ioutil.ReadAll(c.Request.Body)
  19. if err != nil {
  20. global.GVA_LOG.Error(err)
  21. }
  22. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
  23. } else {
  24. body = nil
  25. }
  26. }
  27. }
  28. func OperationRecord() gin.HandlerFunc {
  29. return gin.LoggerWithConfig(gin.LoggerConfig{
  30. Formatter: func(param gin.LogFormatterParams) string {
  31. // 防止加载查询参数,再次过滤
  32. for _, v := range global.GVA_CONFIG.Operation.SkipPaths {
  33. if strings.Contains(param.Path, v) {
  34. return ""
  35. }
  36. }
  37. userId, err := strconv.Atoi(param.Request.Header.Get("x-user-id"))
  38. if err != nil {
  39. userId = 0
  40. }
  41. err = service.CreateSysOperationRecord(model.SysOperationRecord{
  42. Ip: param.ClientIP,
  43. Method: param.Method,
  44. Path: param.Path,
  45. Status: param.StatusCode,
  46. Latency: param.Latency,
  47. Agent: param.Request.UserAgent(),
  48. ErrorMessage: param.ErrorMessage,
  49. Body: string(body),
  50. UserId: userId,
  51. })
  52. if err != nil {
  53. global.GVA_LOG.Error(err)
  54. }
  55. return ""
  56. },
  57. Output: nil,
  58. SkipPaths: global.GVA_CONFIG.Operation.SkipPaths,
  59. })
  60. }