package sls import ( "gitea.drugeyes.vip/pharnexbase/utils/enum" sls "github.com/aliyun/aliyun-log-go-sdk" "github.com/aliyun/aliyun-log-go-sdk/producer" ) type options struct { accessKey string accessSecret string endpoint string project string logstore string } func defaultOptions() *options { return &options{ project: "bcpm-log", logstore: "request-develop", } } // WithEndpoint 指定端口 func WithEndpoint(endpoint string) Option { return func(alc *options) { alc.endpoint = endpoint } } // WithProject 指定发送普通日志的project func WithProject(project string) Option { return func(alc *options) { alc.project = project } } // WithLogstore 指定发送普通日志的logstore func WithLogstore(logstore string) Option { return func(alc *options) { alc.logstore = logstore } } // WithAccessKey 设置访问access id func WithAccessKey(ak string) Option { return func(alc *options) { alc.accessKey = ak } } // WithAccessSecret 设置访问access secret func WithAccessSecret(as string) Option { return func(alc *options) { alc.accessSecret = as } } type Option func(alc *options) type Producer struct { pr *producer.Producer opts *options } // NewSLSProducer 创建一个高性能的sls制造者 func NewSLSProducer(opts ...Option) *Producer { opt := defaultOptions() for _, o := range opts { o(opt) } producerConfig := producer.GetDefaultProducerConfig() producerConfig.Endpoint = opt.endpoint producerConfig.AccessKeyID = opt.accessKey producerConfig.AccessKeySecret = opt.accessSecret producerInstance := producer.InitProducer(producerConfig) producerInstance.Start() return &Producer{ pr: producerInstance, opts: opt, } } // Close 程序结束时,必须调用该方法,不然可能导致部分日志丢失 func (s *Producer) Close() error { return s.pr.Close(5000) } // SendLog 发送普通日志 func (s *Producer) SendLog(topic, source string, log *sls.Log) error { err := s.pr.SendLog(s.opts.project, s.opts.logstore, topic, source, log) if err != nil { return err } return nil } // SendRequestLog 发送特定的请求日志,使用该方法时,不需要指定project和logstore func (s *Producer) SendRequestLog(env enum.Env, req *Request) error { log := GenerateLog(req) err := s.pr.SendLog("bcpm-log", getLogStore(env), "request-go", req.RemoteAddr, log) if err != nil { return err } return nil } func getLogStore(env enum.Env) string { switch env { case enum.Env_local, enum.Env_develop: return "request-develop" case enum.Env_preview: return "request-preview" case enum.Env_production: return "request" default: return "request-develop" } }