fileLog.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package fileLog
  2. import (
  3. "time"
  4. "context"
  5. "encoding/json"
  6. "os"
  7. "go-common/app/service/ops/log-agent/event"
  8. "go-common/app/service/ops/log-agent/processor"
  9. )
  10. const (
  11. _logIdLen = 6
  12. _logLancerHeaderLen = 19
  13. _appIdKey = `"app_id":`
  14. _levelKey = `"level":`
  15. _logTime = `"time":`
  16. )
  17. var (
  18. local, _ = time.LoadLocation("Local")
  19. hostname, _ = os.Hostname()
  20. )
  21. type FileLog struct {
  22. c *Config
  23. }
  24. func init() {
  25. err := processor.Register("fileLog", Process)
  26. if err != nil {
  27. panic(err)
  28. }
  29. }
  30. func Process(ctx context.Context, config interface{}, input <-chan *event.ProcessorEvent) (output chan *event.ProcessorEvent, err error) {
  31. fileLog := new(FileLog)
  32. if c, ok := config.(*Config); !ok {
  33. panic("Error config for jsonLog Processor")
  34. } else {
  35. if err = c.ConfigValidate(); err != nil {
  36. return nil, err
  37. }
  38. fileLog.c = c
  39. }
  40. output = make(chan *event.ProcessorEvent)
  41. go func() {
  42. for {
  43. select {
  44. case e := <-input:
  45. // only do jsonLog for ops-log
  46. if e.Destination != "lancer-ops-log" {
  47. output <- e
  48. continue
  49. }
  50. // format message
  51. message := make(map[string]interface{})
  52. if len(e.ParsedFields) != 0 {
  53. for k, v := range e.ParsedFields {
  54. message[k] = v
  55. }
  56. }
  57. message["log"] = e.String()
  58. e.Fields["hostname"] = hostname
  59. if len(e.Tags) != 0 {
  60. e.Fields["tag"] = e.Tags
  61. }
  62. if len(e.Fields) != 0 {
  63. message["fields"] = e.Fields
  64. }
  65. message["app_id"] = string(e.AppId)
  66. message["time"] = e.Time.UTC().Format(time.RFC3339Nano)
  67. if body, err := json.Marshal(message); err == nil {
  68. e.Write(body)
  69. output <- e
  70. }
  71. case <-ctx.Done():
  72. return
  73. }
  74. }
  75. }()
  76. return output, nil
  77. }