graylog.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package graylog
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/robertkowalski/graylog-golang"
  6. "miads/adslib"
  7. "miads/adslib/utils"
  8. "net/url"
  9. "time"
  10. log "github.com/sirupsen/logrus"
  11. )
  12. var grayLog *gelf.Gelf
  13. func init() {
  14. grayLog = gelf.New(gelf.Config{
  15. GraylogPort: 62002,
  16. GraylogHostname: "172.18.199.72",
  17. Connection: "lan",
  18. MaxChunkSizeWan: 42,
  19. MaxChunkSizeLan: 1337,
  20. })
  21. }
  22. func Log(logData interface{}) {
  23. logStr, _ := json.Marshal(logData)
  24. log.Infof("graylog: %s", logStr)
  25. grayLog.Log(string(logStr))
  26. }
  27. func LogApi(shortMsg string, desc string, extraDesc string, reqSource string) {
  28. grayLogData := struct {
  29. ShortMessage string `json:"short_message"`
  30. ReqSource string `json:"req_source"`
  31. AdsDetail string `json:"ads_detail"`
  32. AdsExtraDetail string `json:"ads_extra_detail"`
  33. }{
  34. ShortMessage: shortMsg,
  35. ReqSource: reqSource,
  36. AdsDetail: desc,
  37. AdsExtraDetail: extraDesc,
  38. }
  39. Log(grayLogData)
  40. }
  41. // 发送返回日志
  42. func ReportGrayLog(req adslib.Request, dsp utils.DspParam, uid int, jsonFlag int) {
  43. gelfData := make(map[string]interface{}, 100)
  44. gelfData["short_message"] = "ads_api_log"
  45. gelfData["_user_id"] = uid
  46. gelfData["_device_id"] = req.DeviceId
  47. gelfData["_ip"] = dsp.Ip
  48. gelfData["_uri"] = req.QueryString
  49. gelfData["_province"] = dsp.Province
  50. gelfData["_city"] = dsp.City
  51. gelfData["_city_code"] = dsp.DspCityCode
  52. var reqData url.Values
  53. if jsonFlag == 0 {
  54. reqData, _ = url.ParseQuery(req.QueryString)
  55. } else {
  56. err := json.Unmarshal([]byte(req.Body), &reqData)
  57. if err != nil {
  58. fmt.Print("parse error")
  59. }
  60. }
  61. for k, v := range reqData {
  62. if k == "ip" {
  63. continue
  64. }
  65. gelfData["_"+k] = v
  66. }
  67. gelfData["_request"] = reqData.Encode()
  68. gelfData["_response"] = ""
  69. gelfData["_response_time"] = time.Now().UnixNano() / 1000
  70. Log(gelfData)
  71. }