grlogs/logs/alils/alils.go

99 lines
2.4 KiB
Go
Raw Permalink 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"
"os"
2020-05-07 10:59:16 +08:00
"runtime"
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"`
Debug bool
}
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-07 10:59:16 +08:00
producerConfig.NoRetryStatusCodeList = []int{-1}
producerConfig.Retries = 2
producerConfig.AllowLogLevel = "error"
2020-05-07 10:59:16 +08:00
producerConfig.MaxIoWorkerCount = int64(runtime.NumCPU())
2020-05-04 21:10:20 +08:00
a.producer = producer.InitProducer(producerConfig)
a.callback = &Callback{}
a.producer.Start()
a.Debug = os.Getenv("GRLOG_ALILS_DEBUG") == "on"
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
if a.Debug {
2020-05-07 10:59:16 +08:00
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
}
2020-05-05 16:10:42 +08:00
}
}
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)
}