1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package zlog
- import (
- "encoding/json"
- "log"
- "time"
- sls "github.com/aliyun/aliyun-log-go-sdk"
- "google.golang.org/protobuf/proto"
- )
- type SLSWriter struct {
- cfg SLSWriterConfig
- client sls.ClientInterface
- project *sls.LogProject
- logStore *sls.LogStore
- }
- type SLSWriterConfig struct {
- Endpoint string
- AccessKeyId string
- AccessKeySecret string
- ProjectName string
- LogStoreName string
- Topic string
- SourceIP string
- Environment string
- }
- func NewSLSWriter(cfg SLSWriterConfig) *SLSWriter {
- // Create a logging service client.
- provider := sls.NewStaticCredentialsProvider(cfg.AccessKeyId, cfg.AccessKeySecret, "")
- client := sls.CreateNormalInterfaceV2(cfg.Endpoint, provider)
- project, err := client.GetProject(cfg.ProjectName)
- if err != nil {
- log.Fatalln(err)
- }
- logStore, err := client.GetLogStore(project.Name, cfg.LogStoreName)
- if err != nil {
- log.Fatalln(err)
- }
- return &SLSWriter{
- cfg: cfg,
- client: client,
- project: project,
- logStore: logStore,
- }
- }
- func (w *SLSWriter) GetEnv() string {
- return w.cfg.Environment
- }
- func (w *SLSWriter) Write(p []byte) (int, error) {
- var err error
- var attributes map[string]string
- if err = json.Unmarshal(p, &attributes); err != nil {
- return 0, err
- }
- contents := make([]*sls.LogContent, 0)
- for k, v := range attributes {
- contents = append(contents, &sls.LogContent{Key: proto.String(k), Value: proto.String(v)})
- }
- unix := uint32(time.Now().UTC().Unix())
- logs := []*sls.Log{
- {
- Time: proto.Uint32(unix),
- Contents: contents,
- },
- }
- lg := &sls.LogGroup{
- Topic: proto.String(w.cfg.Topic),
- Source: proto.String(w.cfg.SourceIP),
- Logs: logs,
- }
- return 1, w.client.PutLogs(w.project.Name, w.logStore.Name, lg)
- }
|