logger_cassandra.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. package middleware
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "git.qianqiusoft.com/qianqiusoft/light-apiengine/config"
  7. "github.com/gin-gonic/gin"
  8. "github.com/gocql/gocql"
  9. "strings"
  10. "time"
  11. )
  12. var __logInfoChan chan *logInfo
  13. // cassandra 配置
  14. var _clusterCfg *gocql.ClusterConfig = nil
  15. // app名称
  16. var __appName string = ""
  17. func init(){
  18. defer func() {
  19. if p := recover(); p != nil {
  20. fmt.Println("ecover", p)
  21. }
  22. }()
  23. // 设置app名称
  24. __appName = config.AppConfig.GetKey("app_name")
  25. __logInfoChan = make(chan *logInfo, 1000)
  26. // 设置cassandar 配置
  27. cassandra := config.AppConfig.GetKey("cassandra")
  28. _clusterCfg = gocql.NewCluster(strings.Split(cassandra, ",")...)
  29. _clusterCfg.Keyspace = "i2_log"
  30. _clusterCfg.Consistency = gocql.Quorum
  31. //设置连接池的数量,默认是2个(针对每一个host,都建立起NumConns个连接)
  32. _clusterCfg.NumConns = 3
  33. session, err := _clusterCfg.CreateSession()
  34. if err != nil{
  35. fmt.Println("create session err", err.Error())
  36. return
  37. }
  38. time.Sleep(1 * time.Second) //Sleep so the fillPool can complete.
  39. defer session.Close()
  40. // 日志处理
  41. logProcess()
  42. }
  43. /**
  44. * 自定义日志响应类,主要是把resp的响应内容写入到body中
  45. */
  46. type loggerRespWriter struct{
  47. gin.ResponseWriter
  48. respBody *bytes.Buffer
  49. }
  50. // 写字节数组
  51. func (w loggerRespWriter) Write(b []byte) (int, error) {
  52. w.respBody.Write(b) // 保存
  53. return w.ResponseWriter.Write(b)
  54. }
  55. // 写字符串
  56. func (w loggerRespWriter) WriteString(s string) (int, error) {
  57. w.respBody.WriteString(s) // 保存
  58. return w.ResponseWriter.WriteString(s)
  59. }
  60. /**
  61. * 日志信息
  62. */
  63. type logInfo struct {
  64. ReqClientIp string
  65. ReqTime time.Time
  66. ReqMethod string
  67. ReqUrl string
  68. ReqProto string
  69. ReqUa string
  70. ReqReferer string
  71. ReqPostData string
  72. RespTime time.Time
  73. RespBody string
  74. RespCode string // 由 resp body 解析
  75. RespMsg string // 由 resp body 解析
  76. RespData string // 由 resp body 解析
  77. CostTime int
  78. }
  79. func LoggerCassandra()gin.HandlerFunc{
  80. return func(c *gin.Context){
  81. respWriter := &loggerRespWriter{
  82. ResponseWriter: c.Writer,
  83. respBody: bytes.NewBuffer([]byte{}),
  84. }
  85. c.Writer = respWriter // 注入自定writer
  86. logInfo := &logInfo{}
  87. logInfo.ReqTime = time.Now()
  88. // 下一个请求
  89. c.Next()
  90. // 设置对象
  91. logInfo.RespBody = respWriter.respBody.String()
  92. logInfo.RespTime = time.Now()
  93. logInfo.ReqMethod = c.Request.Method
  94. logInfo.ReqUrl = c.Request.RequestURI
  95. logInfo.ReqProto = c.Request.Proto
  96. logInfo.ReqUa = c.Request.UserAgent()
  97. logInfo.ReqReferer = c.Request.Referer()
  98. logInfo.ReqPostData = c.Request.PostForm.Encode()
  99. logInfo.ReqClientIp = c.ClientIP()
  100. __logInfoChan <- logInfo
  101. }
  102. }
  103. func logProcess(){
  104. go func(){
  105. for{
  106. select {
  107. case logInfo := <- __logInfoChan:
  108. insertLogInfo(logInfo)
  109. }
  110. }
  111. }()
  112. }
  113. func insertLogInfo(logInfo *logInfo){
  114. session, err := _clusterCfg.CreateSession()
  115. if err != nil{
  116. fmt.Println("创建cassandra session错误", err.Error())
  117. return
  118. }
  119. defer session.Close()
  120. var respBodyObj struct {
  121. Code string
  122. Msg string
  123. Data string
  124. }
  125. if logInfo.RespBody != ""{
  126. err = json.Unmarshal([]byte(logInfo.RespBody), &respBodyObj)
  127. if err != nil{
  128. fmt.Println("json.Unmarshal 错误", err.Error())
  129. }else {
  130. logInfo.RespCode = respBodyObj.Code
  131. logInfo.RespMsg = respBodyObj.Msg
  132. logInfo.RespData = respBodyObj.Data
  133. }
  134. }
  135. logInfo.CostTime = int(logInfo.RespTime.Sub(logInfo.ReqTime))
  136. // 保存轨迹
  137. fmt.Println("保存轨迹")
  138. cqlformat := `insert into
  139. log_info(app_name, req_date, req_time, req_method, req_url, req_proto, req_ua, req_referer, req_post_data, resp_time, resp_body, resp_code, resp_msg, resp_data, cost_time)
  140. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);`
  141. reqDate := logInfo.ReqTime.Format("20060102")
  142. q := session.Query(cqlformat, __appName, reqDate, logInfo.ReqTime.Format("2006-01-02 15:04:05"), logInfo.ReqMethod, logInfo.ReqUrl, logInfo.ReqProto, logInfo.ReqUa, logInfo.ReqReferer, logInfo.ReqPostData, logInfo.RespTime.Format("2006-01-02 15:04:05"), logInfo.RespBody, logInfo.RespCode, logInfo.RespMsg, logInfo.RespData, logInfo.CostTime)
  143. err = q.Exec() // 应该可以使用批量插入
  144. if err != nil{
  145. fmt.Println("插入日志错误:", err)
  146. return
  147. }
  148. }