graylog.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. }
  26. func LogApi(shortMsg string, desc string, extraDesc string, reqSource string) {
  27. grayLogData := struct {
  28. ShortMessage string `json:"short_message"`
  29. ReqSource string `json:"req_source"`
  30. AdsDetail string `json:"ads_detail"`
  31. AdsExtraDetail string `json:"ads_extra_detail"`
  32. }{
  33. ShortMessage: shortMsg,
  34. ReqSource: reqSource,
  35. AdsDetail: desc,
  36. AdsExtraDetail: extraDesc,
  37. }
  38. Log(grayLogData)
  39. }
  40. // 发送返回日志
  41. func ReportGrayLog(req adslib.Request, dsp utils.DspParam, uid int, jsonFlag int) {
  42. gelfData := make(map[string]interface{}, 100)
  43. gelfData["short_message"] = "ads_api_log"
  44. gelfData["_user_id"] = uid
  45. gelfData["_device_id"] = req.DeviceId
  46. gelfData["_ip"] = dsp.Ip
  47. gelfData["_uri"] = req.QueryString
  48. gelfData["_province"]=dsp.Province
  49. gelfData["_city"]=dsp.City
  50. gelfData["_city_code"]=dsp.DspCityCode
  51. var reqData url.Values
  52. if jsonFlag == 0 {
  53. reqData, _ = url.ParseQuery(req.QueryString)
  54. } else {
  55. err := json.Unmarshal([]byte(req.Body), &reqData)
  56. if err != nil {
  57. fmt.Print("parse error")
  58. }
  59. }
  60. for k, v := range reqData {
  61. if k == "ip" {
  62. continue
  63. }
  64. gelfData["_" + k] = v
  65. }
  66. gelfData["_request"] = reqData.Encode()
  67. gelfData["_response"] = ""
  68. gelfData["_response_time"] = time.Now().UnixNano() / 1000
  69. Log(gelfData)
  70. }