sample.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package sample
  2. import (
  3. "math/rand"
  4. "context"
  5. "go-common/app/service/ops/log-agent/event"
  6. "go-common/app/service/ops/log-agent/processor"
  7. "go-common/app/service/ops/log-agent/pkg/common"
  8. "go-common/app/service/ops/log-agent/pkg/flowmonitor"
  9. )
  10. type Sample struct {
  11. c *Config
  12. }
  13. func init() {
  14. err := processor.Register("sample", Process)
  15. if err != nil {
  16. panic(err)
  17. }
  18. }
  19. func Process(ctx context.Context, config interface{}, input <-chan *event.ProcessorEvent) (output chan *event.ProcessorEvent, err error) {
  20. sample := new(Sample)
  21. if c, ok := config.(*Config); !ok {
  22. panic("Error config for sample Processor")
  23. } else {
  24. if err = c.ConfigValidate(); err != nil {
  25. return nil, err
  26. }
  27. sample.c = c
  28. }
  29. output = make(chan *event.ProcessorEvent)
  30. go func() {
  31. for {
  32. select {
  33. case e := <-input:
  34. // only do sample for ops-log
  35. if e.Destination != "lancer-ops-log" {
  36. output <- e
  37. continue
  38. }
  39. if !sample.sample(e) {
  40. output <- e
  41. } else {
  42. flowmonitor.Fm.AddEvent(e, "log-agent.processor.sample", "WARN", "sampled")
  43. event.PutEvent(e)
  44. }
  45. case <-ctx.Done():
  46. return
  47. }
  48. }
  49. }()
  50. return output, nil
  51. }
  52. //sample log, if return ture, the log should be discard
  53. func (s *Sample) sample(e *event.ProcessorEvent) bool {
  54. if common.CriticalLog(e.Level) {
  55. return false // keep log if level isn't INFO or DEBUG
  56. }
  57. if e.Priority == "high" {
  58. return false
  59. }
  60. if val, ok := s.c.SampleConfig[string(e.AppId)]; ok {
  61. if rand.Intn(100) < 100-int(val) {
  62. return true // discard
  63. }
  64. }
  65. return false
  66. }