高热共公日志库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.4 KiB

  1. package alils
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/aliyun/aliyun-log-go-sdk/producer"
  6. "golib.gaore.com/GaoreGo/grlogs/logs"
  7. "os"
  8. "runtime"
  9. "time"
  10. )
  11. func NewAliLS() logs.Logger {
  12. cw := &alilsLogger{
  13. Level: logs.LevelDebug,
  14. }
  15. return cw
  16. }
  17. type alilsLogger struct {
  18. producer *producer.Producer
  19. callback *Callback
  20. Project string `json:"project"`
  21. Endpoint string `json:"endpoint"`
  22. KeyID string `json:"key_id"`
  23. KeySecret string `json:"key_secret"`
  24. LogStore string `json:"log_store"`
  25. Topics []string `json:"topics"`
  26. Source string `json:"source"`
  27. Level int `json:"level"`
  28. FlushWhen int `json:"flush_when"`
  29. Debug bool
  30. }
  31. func (a *alilsLogger) Init(jsonconfig string) error {
  32. err := json.Unmarshal([]byte(jsonconfig), a)
  33. if err != nil {
  34. return err
  35. }
  36. producerConfig := producer.GetDefaultProducerConfig()
  37. producerConfig.Endpoint = a.Endpoint
  38. producerConfig.AccessKeyID = a.KeyID
  39. producerConfig.AccessKeySecret = a.KeySecret
  40. producerConfig.LingerMs = 100
  41. producerConfig.NoRetryStatusCodeList = []int{-1}
  42. producerConfig.Retries = 2
  43. producerConfig.AllowLogLevel = "error"
  44. producerConfig.MaxIoWorkerCount = int64(runtime.NumCPU())
  45. a.producer = producer.InitProducer(producerConfig)
  46. a.callback = &Callback{}
  47. a.producer.Start()
  48. a.Debug = os.Getenv("GRLOG_ALILS_DEBUG") == "on"
  49. return nil
  50. }
  51. func (a *alilsLogger) WriteMsg(when time.Time, msg string, level int, lable string, env string) error {
  52. vals := map[string]string{"msg": msg, "level": fmt.Sprintf("%d", level)}
  53. vals["level_string"] = logs.GetLevelString(level)
  54. vals["env"] = env
  55. vals["lable"] = lable
  56. vals["hostname"] = GetHostname()
  57. vals["working_idr"] = Getwd()
  58. vals["home_dir"] = GetUserHomename()
  59. vals["hardware_addr"] = GetCurrentInterfaceHardwareAddr()
  60. vals["client_addrs"] = GetCurrentInterfaceAddrs()
  61. log := producer.GenerateLog(uint32(when.Unix()), vals)
  62. if a.Debug {
  63. for _, topic := range a.Topics {
  64. if err := a.producer.SendLogWithCallBack(a.Project, a.LogStore, topic, a.Source, log, a.callback); err != nil {
  65. return err
  66. }
  67. }
  68. } else {
  69. for _, topic := range a.Topics {
  70. if err := a.producer.SendLog(a.Project, a.LogStore, topic, a.Source, log); err != nil {
  71. return err
  72. }
  73. }
  74. }
  75. return nil
  76. }
  77. func (a *alilsLogger) Destroy() {
  78. a.producer.SafeClose()
  79. a.producer.Close(300)
  80. }
  81. func (a *alilsLogger) Flush() {
  82. }
  83. func init() {
  84. logs.Register(logs.AdapterAliLS, NewAliLS)
  85. }