logger.go 3.6 KB

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