graylog.go 1.8 KB

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