github.com/jtzjtz/kit@v1.0.2/conn/sls_producer.go (about)

     1  package conn
     2  
     3  import (
     4  	"errors"
     5  	sls "github.com/aliyun/aliyun-log-go-sdk"
     6  	"github.com/aliyun/aliyun-log-go-sdk/producer"
     7  	"time"
     8  )
     9  
    10  type LogProjectConf struct {
    11  	Project  string
    12  	Logstore string
    13  	Topic    string
    14  	Source   string
    15  }
    16  
    17  var SLSProducer *producer.Producer
    18  var accessProject, accesslogstore, _topic, _source string
    19  var defaultAccessLog, defaultInfoLog, defaultErrorLog LogProjectConf
    20  
    21  //初始化SLSProducer,设置默认project logstore,topic,source
    22  func InitSLSProducer(producerConfig *producer.ProducerConfig) {
    23  	SLSProducer = producer.InitProducer(producerConfig)
    24  	SLSProducer.Start()
    25  	PutNewConn(func() { //程序关闭时调用conn.Close()
    26  		SLSProducer.SafeClose()
    27  	})
    28  }
    29  func SetDefaultAccessLog(project, logstore, topic, source string) {
    30  	defaultAccessLog.Source = source
    31  	defaultAccessLog.Topic = topic
    32  	defaultAccessLog.Logstore = logstore
    33  	defaultAccessLog.Project = project
    34  }
    35  func GetDefaultAccessLogConfig() LogProjectConf {
    36  	return defaultAccessLog
    37  }
    38  
    39  func SetDefaultInfoLog(project, logstore, topic, source string) {
    40  	defaultInfoLog.Source = source
    41  	defaultInfoLog.Topic = topic
    42  	defaultInfoLog.Logstore = logstore
    43  	defaultInfoLog.Project = project
    44  }
    45  func GetDefaultInfoLogConfig() LogProjectConf {
    46  	return defaultInfoLog
    47  }
    48  func SetDefaultErrorLog(project, logstore, topic, source string) {
    49  	defaultErrorLog.Source = source
    50  	defaultErrorLog.Topic = topic
    51  	defaultErrorLog.Logstore = logstore
    52  	defaultErrorLog.Project = project
    53  }
    54  func GetDefaultErrorLogConfig() LogProjectConf {
    55  	return defaultErrorLog
    56  }
    57  
    58  //发送map类型数据到logstore
    59  func SendMap(data map[string]string, project LogProjectConf) error {
    60  	log := producer.GenerateLog(uint32(time.Now().Unix()), data)
    61  	if SLSProducer == nil || len(project.Project) == 0 || len(project.Logstore) == 0 {
    62  		return errors.New("SLSProducer未初始化")
    63  	}
    64  	return SLSProducer.SendLog(project.Project, project.Logstore, project.Topic, project.Source, log)
    65  }
    66  
    67  //发送log类型数据到logstore
    68  func SendLog(log *sls.Log, project LogProjectConf) error {
    69  	if SLSProducer == nil || len(project.Project) == 0 || len(project.Logstore) == 0 {
    70  		return errors.New("SLSProducer未初始化")
    71  	}
    72  	return SLSProducer.SendLog(project.Project, project.Logstore, project.Topic, project.Source, log)
    73  }