logger.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. package middleware
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/json"
  6. "go-admin/app/admin/service/dto"
  7. "go-admin/common"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "strings"
  12. "time"
  13. "github.com/gin-gonic/gin"
  14. "github.com/go-admin-team/go-admin-core/sdk"
  15. "github.com/go-admin-team/go-admin-core/sdk/api"
  16. "github.com/go-admin-team/go-admin-core/sdk/config"
  17. "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
  18. "go-admin/common/global"
  19. )
  20. // LoggerToFile 日志记录到文件
  21. func LoggerToFile() gin.HandlerFunc {
  22. return func(c *gin.Context) {
  23. log := api.GetRequestLogger(c)
  24. // 开始时间
  25. startTime := time.Now()
  26. // 处理请求
  27. var body string
  28. switch c.Request.Method {
  29. case http.MethodPost, http.MethodPut, http.MethodGet, http.MethodDelete:
  30. bf := bytes.NewBuffer(nil)
  31. wt := bufio.NewWriter(bf)
  32. _, err := io.Copy(wt, c.Request.Body)
  33. if err != nil {
  34. log.Warnf("copy body error, %s", err.Error())
  35. err = nil
  36. }
  37. rb, _ := ioutil.ReadAll(bf)
  38. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(rb))
  39. body = string(rb)
  40. }
  41. c.Next()
  42. url := c.Request.RequestURI
  43. if strings.Index(url, "logout") > -1 ||
  44. strings.Index(url, "login") > -1 {
  45. return
  46. }
  47. // 结束时间
  48. endTime := time.Now()
  49. if c.Request.Method == http.MethodOptions {
  50. return
  51. }
  52. rt, bl := c.Get("result")
  53. var result = ""
  54. if bl {
  55. rb, err := json.Marshal(rt)
  56. if err != nil {
  57. log.Warnf("json Marshal result error, %s", err.Error())
  58. } else {
  59. result = string(rb)
  60. }
  61. }
  62. st, bl := c.Get("status")
  63. var statusBus = 0
  64. if bl {
  65. statusBus = st.(int)
  66. }
  67. // 请求方式
  68. reqMethod := c.Request.Method
  69. // 请求路由
  70. reqUri := c.Request.RequestURI
  71. // 状态码
  72. statusCode := c.Writer.Status()
  73. // 请求IP
  74. clientIP := common.GetClientIP(c)
  75. // 执行时间
  76. latencyTime := endTime.Sub(startTime)
  77. // 日志格式
  78. logData := map[string]interface{}{
  79. "statusCode": statusCode,
  80. "latencyTime": latencyTime,
  81. "clientIP": clientIP,
  82. "method": reqMethod,
  83. "uri": reqUri,
  84. }
  85. log.WithFields(logData).Info()
  86. if c.Request.Method != "OPTIONS" && config.LoggerConfig.EnabledDB && statusCode != 404 {
  87. SetDBOperLog(c, clientIP, statusCode, reqUri, reqMethod, latencyTime, body, result, statusBus)
  88. }
  89. }
  90. }
  91. // SetDBOperLog 写入操作日志表 fixme 该方法后续即将弃用
  92. func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string, reqMethod string, latencyTime time.Duration, body string, result string, status int) {
  93. log := api.GetRequestLogger(c)
  94. l := make(map[string]interface{})
  95. l["_fullPath"] = c.FullPath()
  96. l["operUrl"] = reqUri
  97. l["operIp"] = clientIP
  98. l["operLocation"] = "" // pkg.GetLocation(clientIP, gaConfig.ExtConfig.AMap.Key)
  99. l["operName"] = user.GetUserName(c)
  100. l["requestMethod"] = reqMethod
  101. l["operParam"] = body
  102. l["operTime"] = time.Now()
  103. l["jsonResult"] = result
  104. l["latencyTime"] = latencyTime.String()
  105. l["statusCode"] = statusCode
  106. l["userAgent"] = c.Request.UserAgent()
  107. l["createBy"] = user.GetUserId(c)
  108. l["updateBy"] = user.GetUserId(c)
  109. if status == http.StatusOK {
  110. l["status"] = dto.OperaStatusEnabel
  111. } else {
  112. l["status"] = dto.OperaStatusDisable
  113. }
  114. q := sdk.Runtime.GetMemoryQueue(c.Request.Host)
  115. message, err := sdk.Runtime.GetStreamMessage("", global.OperateLog, l)
  116. if err != nil {
  117. log.Errorf("GetStreamMessage error, %s", err.Error())
  118. //日志报错错误,不中断请求
  119. } else {
  120. err = q.Append(message)
  121. if err != nil {
  122. log.Errorf("Append message error, %s", err.Error())
  123. }
  124. }
  125. }