log_sink.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2021-2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package sink
  15. import (
  16. "fmt"
  17. "sync"
  18. "time"
  19. "github.com/lf-edge/ekuiper/internal/topo/collector"
  20. "github.com/lf-edge/ekuiper/pkg/api"
  21. )
  22. // NewLogSink log action, no properties now
  23. // example: {"log":{}}
  24. func NewLogSink() api.Sink {
  25. return collector.Func(func(ctx api.StreamContext, data interface{}) error {
  26. log := ctx.GetLogger()
  27. if v, _, err := ctx.TransformOutput(data); err == nil {
  28. log.Infof("sink result for rule %s: %s", ctx.GetRuleId(), v)
  29. return nil
  30. } else {
  31. return fmt.Errorf("transform data error: %v", err)
  32. }
  33. })
  34. }
  35. type QueryResult struct {
  36. Results []string
  37. LastFetch time.Time
  38. Mux sync.Mutex
  39. }
  40. var QR = &QueryResult{LastFetch: time.Now()}
  41. func NewLogSinkToMemory() api.Sink {
  42. QR.Results = make([]string, 0, 10)
  43. return collector.Func(func(ctx api.StreamContext, data interface{}) error {
  44. var result string
  45. if v, _, err := ctx.TransformOutput(data); err == nil {
  46. result = string(v)
  47. } else {
  48. return fmt.Errorf("transform data error: %v", err)
  49. }
  50. QR.Mux.Lock()
  51. QR.Results = append(QR.Results, result)
  52. QR.Mux.Unlock()
  53. return nil
  54. })
  55. }