logs.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package formatter
  14. import (
  15. "bytes"
  16. "context"
  17. "fmt"
  18. "io"
  19. "strconv"
  20. "strings"
  21. )
  22. // NewLogConsumer creates a new LogConsumer
  23. func NewLogConsumer(ctx context.Context, w io.Writer) LogConsumer {
  24. return LogConsumer{
  25. ctx: ctx,
  26. colors: map[string]colorFunc{},
  27. width: 0,
  28. writer: w,
  29. }
  30. }
  31. // Log formats a log message as received from service/container
  32. func (l *LogConsumer) Log(service, container, message string) {
  33. if l.ctx.Err() != nil {
  34. return
  35. }
  36. cf, ok := l.colors[service]
  37. if !ok {
  38. cf = <-loop
  39. l.colors[service] = cf
  40. l.computeWidth()
  41. }
  42. prefix := fmt.Sprintf("%-"+strconv.Itoa(l.width)+"s |", service)
  43. for _, line := range strings.Split(message, "\n") {
  44. buf := bytes.NewBufferString(fmt.Sprintf("%s %s\n", cf(prefix), line))
  45. l.writer.Write(buf.Bytes()) // nolint:errcheck
  46. }
  47. }
  48. // GetWriter creates a io.Writer that will actually split by line and format by LogConsumer
  49. func (l *LogConsumer) GetWriter(service, container string) io.Writer {
  50. return splitBuffer{
  51. service: service,
  52. container: container,
  53. consumer: l,
  54. }
  55. }
  56. func (l *LogConsumer) computeWidth() {
  57. width := 0
  58. for n := range l.colors {
  59. if len(n) > width {
  60. width = len(n)
  61. }
  62. }
  63. l.width = width + 3
  64. }
  65. // LogConsumer consume logs from services and format them
  66. type LogConsumer struct {
  67. ctx context.Context
  68. colors map[string]colorFunc
  69. width int
  70. writer io.Writer
  71. }
  72. type splitBuffer struct {
  73. service string
  74. container string
  75. consumer *LogConsumer
  76. }
  77. func (s splitBuffer) Write(b []byte) (n int, err error) {
  78. split := bytes.Split(b, []byte{'\n'})
  79. for _, line := range split {
  80. if len(line) != 0 {
  81. s.consumer.Log(s.service, s.container, string(line))
  82. }
  83. }
  84. return len(b), nil
  85. }