97 lines
2.4 KiB
Go
97 lines
2.4 KiB
Go
package alils
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/aliyun/aliyun-log-go-sdk/producer"
|
|
"golib.gaore.com/GaoreGo/grlogs/logs"
|
|
"runtime"
|
|
"time"
|
|
)
|
|
|
|
func NewAliLS() logs.Logger {
|
|
cw := &alilsLogger{
|
|
Level: logs.LevelDebug,
|
|
}
|
|
return cw
|
|
}
|
|
|
|
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"`
|
|
}
|
|
|
|
func (a *alilsLogger) Init(jsonconfig string) error {
|
|
|
|
err := json.Unmarshal([]byte(jsonconfig), a)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
producerConfig := producer.GetDefaultProducerConfig()
|
|
producerConfig.Endpoint = a.Endpoint
|
|
producerConfig.AccessKeyID = a.KeyID
|
|
producerConfig.AccessKeySecret = a.KeySecret
|
|
producerConfig.LingerMs = 100
|
|
producerConfig.NoRetryStatusCodeList = []int{-1}
|
|
producerConfig.Retries = 2
|
|
producerConfig.AllowLogLevel = "err"
|
|
producerConfig.MaxIoWorkerCount = int64(runtime.NumCPU())
|
|
a.producer = producer.InitProducer(producerConfig)
|
|
a.callback = &Callback{}
|
|
a.producer.Start()
|
|
|
|
return nil
|
|
}
|
|
|
|
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)
|
|
|
|
if env == "dev" || env == "test" {
|
|
for _, topic := range a.Topics {
|
|
if err := a.producer.SendLogWithCallBack(a.Project, a.LogStore, topic, a.Source, log, a.callback); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
} else {
|
|
for _, topic := range a.Topics {
|
|
if err := a.producer.SendLog(a.Project, a.LogStore, topic, a.Source, log); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *alilsLogger) Destroy() {
|
|
a.producer.SafeClose()
|
|
a.producer.Close(300)
|
|
}
|
|
|
|
func (a *alilsLogger) Flush() {
|
|
|
|
}
|
|
|
|
func init() {
|
|
logs.Register(logs.AdapterAliLS, NewAliLS)
|
|
}
|