write_sls.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package zlog
  2. import (
  3. "encoding/json"
  4. "log"
  5. "time"
  6. sls "github.com/aliyun/aliyun-log-go-sdk"
  7. "google.golang.org/protobuf/proto"
  8. )
  9. type SLSWriter struct {
  10. cfg SLSWriterConfig
  11. client sls.ClientInterface
  12. project *sls.LogProject
  13. logStore *sls.LogStore
  14. }
  15. type SLSWriterConfig struct {
  16. Endpoint string
  17. AccessKeyId string
  18. AccessKeySecret string
  19. ProjectName string
  20. LogStoreName string
  21. Topic string
  22. SourceIP string
  23. Environment string
  24. }
  25. func NewSLSWriter(cfg SLSWriterConfig) *SLSWriter {
  26. // Create a logging service client.
  27. provider := sls.NewStaticCredentialsProvider(cfg.AccessKeyId, cfg.AccessKeySecret, "")
  28. client := sls.CreateNormalInterfaceV2(cfg.Endpoint, provider)
  29. project, err := client.GetProject(cfg.ProjectName)
  30. if err != nil {
  31. log.Fatalln(err)
  32. }
  33. logStore, err := client.GetLogStore(project.Name, cfg.LogStoreName)
  34. if err != nil {
  35. log.Fatalln(err)
  36. }
  37. return &SLSWriter{
  38. cfg: cfg,
  39. client: client,
  40. project: project,
  41. logStore: logStore,
  42. }
  43. }
  44. func (w *SLSWriter) GetEnv() string {
  45. return w.cfg.Environment
  46. }
  47. func (w *SLSWriter) Write(p []byte) (int, error) {
  48. var err error
  49. var attributes map[string]string
  50. if err = json.Unmarshal(p, &attributes); err != nil {
  51. return 0, err
  52. }
  53. contents := make([]*sls.LogContent, 0)
  54. for k, v := range attributes {
  55. contents = append(contents, &sls.LogContent{Key: proto.String(k), Value: proto.String(v)})
  56. }
  57. unix := uint32(time.Now().UTC().Unix())
  58. logs := []*sls.Log{
  59. {
  60. Time: proto.Uint32(unix),
  61. Contents: contents,
  62. },
  63. }
  64. lg := &sls.LogGroup{
  65. Topic: proto.String(w.cfg.Topic),
  66. Source: proto.String(w.cfg.SourceIP),
  67. Logs: logs,
  68. }
  69. return 1, w.client.PutLogs(w.project.Name, w.logStore.Name, lg)
  70. }