copier.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package logger
  2. import (
  3. "bufio"
  4. "bytes"
  5. "io"
  6. "sync"
  7. "time"
  8. "github.com/Sirupsen/logrus"
  9. )
  10. // Copier can copy logs from specified sources to Logger and attach
  11. // ContainerID and Timestamp.
  12. // Writes are concurrent, so you need implement some sync in your logger
  13. type Copier struct {
  14. // cid is the container id for which we are copying logs
  15. cid string
  16. // srcs is map of name -> reader pairs, for example "stdout", "stderr"
  17. srcs map[string]io.Reader
  18. dst Logger
  19. copyJobs sync.WaitGroup
  20. }
  21. // NewCopier creates a new Copier
  22. func NewCopier(cid string, srcs map[string]io.Reader, dst Logger) *Copier {
  23. return &Copier{
  24. cid: cid,
  25. srcs: srcs,
  26. dst: dst,
  27. }
  28. }
  29. // Run starts logs copying
  30. func (c *Copier) Run() {
  31. for src, w := range c.srcs {
  32. c.copyJobs.Add(1)
  33. go c.copySrc(src, w)
  34. }
  35. }
  36. func (c *Copier) copySrc(name string, src io.Reader) {
  37. defer c.copyJobs.Done()
  38. reader := bufio.NewReader(src)
  39. for {
  40. line, err := reader.ReadBytes('\n')
  41. line = bytes.TrimSuffix(line, []byte{'\n'})
  42. // ReadBytes can return full or partial output even when it failed.
  43. // e.g. it can return a full entry and EOF.
  44. if err == nil || len(line) > 0 {
  45. if logErr := c.dst.Log(&Message{ContainerID: c.cid, Line: line, Source: name, Timestamp: time.Now().UTC()}); logErr != nil {
  46. logrus.Errorf("Failed to log msg %q for logger %s: %s", line, c.dst.Name(), logErr)
  47. }
  48. }
  49. if err != nil {
  50. if err != io.EOF {
  51. logrus.Errorf("Error scanning log stream: %s", err)
  52. }
  53. return
  54. }
  55. }
  56. }
  57. // Wait waits until all copying is done
  58. func (c *Copier) Wait() {
  59. c.copyJobs.Wait()
  60. }