copier.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. package logger
  2. import (
  3. "bytes"
  4. "io"
  5. "sync"
  6. "time"
  7. "github.com/sirupsen/logrus"
  8. )
  9. const (
  10. // readSize is the maximum bytes read during a single read
  11. // operation.
  12. readSize = 2 * 1024
  13. // defaultBufSize provides a reasonable default for loggers that do
  14. // not have an external limit to impose on log line size.
  15. defaultBufSize = 16 * 1024
  16. )
  17. // Copier can copy logs from specified sources to Logger and attach Timestamp.
  18. // Writes are concurrent, so you need implement some sync in your logger.
  19. type Copier struct {
  20. // srcs is map of name -> reader pairs, for example "stdout", "stderr"
  21. srcs map[string]io.Reader
  22. dst Logger
  23. copyJobs sync.WaitGroup
  24. closeOnce sync.Once
  25. closed chan struct{}
  26. }
  27. // NewCopier creates a new Copier
  28. func NewCopier(srcs map[string]io.Reader, dst Logger) *Copier {
  29. return &Copier{
  30. srcs: srcs,
  31. dst: dst,
  32. closed: make(chan struct{}),
  33. }
  34. }
  35. // Run starts logs copying
  36. func (c *Copier) Run() {
  37. for src, w := range c.srcs {
  38. c.copyJobs.Add(1)
  39. go c.copySrc(src, w)
  40. }
  41. }
  42. func (c *Copier) copySrc(name string, src io.Reader) {
  43. defer c.copyJobs.Done()
  44. bufSize := defaultBufSize
  45. if sizedLogger, ok := c.dst.(SizedLogger); ok {
  46. bufSize = sizedLogger.BufSize()
  47. }
  48. buf := make([]byte, bufSize)
  49. n := 0
  50. eof := false
  51. for {
  52. select {
  53. case <-c.closed:
  54. return
  55. default:
  56. // Work out how much more data we are okay with reading this time.
  57. upto := n + readSize
  58. if upto > cap(buf) {
  59. upto = cap(buf)
  60. }
  61. // Try to read that data.
  62. if upto > n {
  63. read, err := src.Read(buf[n:upto])
  64. if err != nil {
  65. if err != io.EOF {
  66. logrus.Errorf("Error scanning log stream: %s", err)
  67. return
  68. }
  69. eof = true
  70. }
  71. n += read
  72. }
  73. // If we have no data to log, and there's no more coming, we're done.
  74. if n == 0 && eof {
  75. return
  76. }
  77. // Break up the data that we've buffered up into lines, and log each in turn.
  78. p := 0
  79. for q := bytes.IndexByte(buf[p:n], '\n'); q >= 0; q = bytes.IndexByte(buf[p:n], '\n') {
  80. select {
  81. case <-c.closed:
  82. return
  83. default:
  84. msg := NewMessage()
  85. msg.Source = name
  86. msg.Timestamp = time.Now().UTC()
  87. msg.Line = append(msg.Line, buf[p:p+q]...)
  88. if logErr := c.dst.Log(msg); logErr != nil {
  89. logrus.Errorf("Failed to log msg %q for logger %s: %s", msg.Line, c.dst.Name(), logErr)
  90. }
  91. }
  92. p += q + 1
  93. }
  94. // If there's no more coming, or the buffer is full but
  95. // has no newlines, log whatever we haven't logged yet,
  96. // noting that it's a partial log line.
  97. if eof || (p == 0 && n == len(buf)) {
  98. if p < n {
  99. msg := NewMessage()
  100. msg.Source = name
  101. msg.Timestamp = time.Now().UTC()
  102. msg.Line = append(msg.Line, buf[p:n]...)
  103. msg.Partial = true
  104. if logErr := c.dst.Log(msg); logErr != nil {
  105. logrus.Errorf("Failed to log msg %q for logger %s: %s", msg.Line, c.dst.Name(), logErr)
  106. }
  107. p = 0
  108. n = 0
  109. }
  110. if eof {
  111. return
  112. }
  113. }
  114. // Move any unlogged data to the front of the buffer in preparation for another read.
  115. if p > 0 {
  116. copy(buf[0:], buf[p:n])
  117. n -= p
  118. }
  119. }
  120. }
  121. }
  122. // Wait waits until all copying is done
  123. func (c *Copier) Wait() {
  124. c.copyJobs.Wait()
  125. }
  126. // Close closes the copier
  127. func (c *Copier) Close() {
  128. c.closeOnce.Do(func() {
  129. close(c.closed)
  130. })
  131. }