copier.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package logger
  2. import (
  3. "bufio"
  4. "io"
  5. "sync"
  6. "time"
  7. "github.com/Sirupsen/logrus"
  8. )
  9. // Copier can copy logs from specified sources to Logger and attach
  10. // ContainerID and Timestamp.
  11. // Writes are concurrent, so you need implement some sync in your logger
  12. type Copier struct {
  13. // cid is container id for which we copying logs
  14. cid string
  15. // srcs is map of name -> reader pairs, for example "stdout", "stderr"
  16. srcs map[string]io.Reader
  17. dst Logger
  18. copyJobs sync.WaitGroup
  19. }
  20. // NewCopier creates new Copier
  21. func NewCopier(cid string, srcs map[string]io.Reader, dst Logger) (*Copier, error) {
  22. return &Copier{
  23. cid: cid,
  24. srcs: srcs,
  25. dst: dst,
  26. }, nil
  27. }
  28. // Run starts logs copying
  29. func (c *Copier) Run() {
  30. for src, w := range c.srcs {
  31. c.copyJobs.Add(1)
  32. go c.copySrc(src, w)
  33. }
  34. }
  35. func (c *Copier) copySrc(name string, src io.Reader) {
  36. defer c.copyJobs.Done()
  37. scanner := bufio.NewScanner(src)
  38. for scanner.Scan() {
  39. if err := c.dst.Log(&Message{ContainerID: c.cid, Line: scanner.Bytes(), Source: name, Timestamp: time.Now().UTC()}); err != nil {
  40. logrus.Errorf("Failed to log msg %q for logger %s: %s", scanner.Bytes(), c.dst.Name(), err)
  41. }
  42. }
  43. if err := scanner.Err(); err != nil {
  44. logrus.Errorf("Error scanning log stream: %s", err)
  45. }
  46. }
  47. // Wait waits until all copying is done
  48. func (c *Copier) Wait() {
  49. c.copyJobs.Wait()
  50. }