高热共公日志库
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.

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