logger_cassandra.go 3.8 KB

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