haiwai-grlogs/logs/alils/alils.go

86 lines
2.0 KiB
Go
Raw Normal View History

package alils
import (
"encoding/json"
2020-05-04 21:10:20 +08:00
"fmt"
"github.com/aliyun/aliyun-log-go-sdk/producer"
2020-04-28 14:32:56 +08:00
"golib.gaore.com/GaoreGo/grlogs/logs"
2020-05-04 21:10:20 +08:00
"time"
)
2020-05-04 21:10:20 +08:00
func NewAliLS() logs.Logger {
cw := &alilsLogger{
Level: logs.LevelDebug,
}
return cw
}
2020-05-04 21:10:20 +08:00
type alilsLogger struct {
producer *producer.Producer
callback *Callback
Project string `json:"project"`
Endpoint string `json:"endpoint"`
KeyID string `json:"key_id"`
KeySecret string `json:"key_secret"`
LogStore string `json:"log_store"`
Topics []string `json:"topics"`
Source string `json:"source"`
Level int `json:"level"`
FlushWhen int `json:"flush_when"`
}
2020-05-04 21:10:20 +08:00
func (a *alilsLogger) Init(jsonconfig string) error {
2020-05-04 21:10:20 +08:00
err := json.Unmarshal([]byte(jsonconfig), a)
if err != nil {
return err
}
2020-05-04 21:10:20 +08:00
producerConfig := producer.GetDefaultProducerConfig()
producerConfig.Endpoint = a.Endpoint
producerConfig.AccessKeyID = a.KeyID
producerConfig.AccessKeySecret = a.KeySecret
producerConfig.LingerMs = 100
2020-05-05 17:04:08 +08:00
producerConfig.AllowLogLevel = "error"
2020-05-04 21:10:20 +08:00
a.producer = producer.InitProducer(producerConfig)
a.callback = &Callback{}
a.producer.Start()
return nil
}
2020-05-04 21:10:20 +08:00
func (a *alilsLogger) WriteMsg(when time.Time, msg string, level int, lable string, env string) error {
vals := map[string]string{"msg": msg, "level": fmt.Sprintf("%d", level)}
vals["level_string"] = logs.GetLevelString(level)
vals["env"] = env
vals["lable"] = lable
vals["hostname"] = GetHostname()
vals["working_idr"] = Getwd()
vals["home_dir"] = GetUserHomename()
vals["hardware_addr"] = GetCurrentInterfaceHardwareAddr()
vals["client_addrs"] = GetCurrentInterfaceAddrs()
log := producer.GenerateLog(uint32(when.Unix()), vals)
2020-05-05 16:10:42 +08:00
for _, topic := range a.Topics {
if err := a.producer.SendLog(a.Project, a.LogStore, topic, a.Source, log); err != nil {
return err
}
}
return nil
}
2020-05-04 21:10:20 +08:00
func (a *alilsLogger) Destroy() {
a.producer.SafeClose()
2020-05-05 17:04:08 +08:00
a.producer.Close(300)
}
2020-05-04 21:10:20 +08:00
func (a *alilsLogger) Flush() {
}
func init() {
logs.Register(logs.AdapterAliLS, NewAliLS)
}