git.zd.zone/hrpc/hrpc@v0.0.12/log/cls/cls.go (about) 1 package cls 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "time" 7 8 "git.zd.zone/hrpc/hrpc/configs" 9 "github.com/sirupsen/logrus" 10 clssdk "github.com/tencentcloud/tencentcloud-cls-sdk-go" 11 ) 12 13 type cls struct { 14 Topic string `json:"topic_id"` 15 Credential Credential `json:"credential"` 16 Endpoint string `json:"endpoint"` 17 18 producer *clssdk.AsyncProducerClient 19 opt Options 20 } 21 22 var ( 23 clslog *cls 24 cb *callback 25 ) 26 27 func New(opts ...Option) *cls { 28 opt := Options{ 29 // 默认入口 30 endpoint: "na-siliconvalley.cls.tencentcs.com", 31 callback: nil, 32 } 33 for _, o := range opts { 34 o(&opt) 35 } 36 clslog = &cls{ 37 opt: opt, 38 } 39 return clslog 40 } 41 42 func (c *cls) Load() error { 43 cfg, err := configs.Get().Get("tencent/cls") 44 if err != nil { 45 return err 46 } 47 if err := json.Unmarshal([]byte(cfg), c); err != nil { 48 return err 49 } 50 // option value has highest priority 51 if c.opt.topicID != "" { 52 c.Topic = c.opt.topicID 53 } 54 cb = &callback{ 55 c.opt.callback, 56 } 57 return nil 58 } 59 60 func (c *cls) Name() string { 61 return "hrpc-cls" 62 } 63 64 func (c *cls) DependsOn() []string { 65 return []string{"hrpc-configs"} 66 } 67 68 func (c *cls) Establish() error { 69 if c.producer != nil { 70 // if mutiple Establish() called, close the previous instance first 71 c.producer.Close(3000) 72 } 73 producerConfig := clssdk.GetDefaultAsyncProducerClientConfig() 74 producerConfig.Endpoint = c.opt.endpoint 75 producerConfig.AccessKeyID = c.Credential.SecretID 76 producerConfig.AccessKeySecret = c.Credential.SecretKey 77 producerInstance, err := clssdk.NewAsyncProducerClient(producerConfig) 78 if err != nil { 79 fmt.Println("NewAsyncProducerClient failed, " + err.Error()) 80 return err 81 } 82 producerInstance.Start() 83 c.producer = producerInstance 84 return nil 85 } 86 87 func (c cls) Fire(entry *logrus.Entry) error { 88 if err := c.producer.SendLog( 89 c.Topic, 90 clssdk.NewCLSLog( 91 time.Now().Unix(), 92 logContent(entry), 93 ), cb, 94 ); err != nil { 95 fmt.Println("failed to send log, " + err.Error()) 96 } 97 return nil 98 } 99 100 func logContent(entry *logrus.Entry) map[string]string { 101 var out = map[string]string{ 102 "Level": entry.Level.String(), 103 "Message": entry.Message, 104 "Time": entry.Time.Format("2006-01-02 15:04:05"), 105 } 106 107 d, err := json.Marshal(entry.Data) 108 if err == nil { 109 out["Fields"] = string(d) 110 } 111 112 v, err := json.Marshal(entry.Caller) 113 if err == nil { 114 out["Caller"] = string(v) 115 } 116 return out 117 } 118 119 func (c cls) Levels() []logrus.Level { 120 return []logrus.Level{ 121 logrus.PanicLevel, 122 logrus.FatalLevel, 123 logrus.ErrorLevel, 124 logrus.WarnLevel, 125 logrus.InfoLevel, 126 } 127 } 128 129 func Hook() *cls { 130 return clslog 131 }