logs.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. "github.com/docker/compose-cli/api/compose"
  22. )
  23. // NewLogConsumer creates a new LogConsumer
  24. func NewLogConsumer(ctx context.Context, w io.Writer) compose.LogConsumer {
  25. return &logConsumer{
  26. ctx: ctx,
  27. colors: map[string]colorFunc{},
  28. width: 0,
  29. writer: w,
  30. }
  31. }
  32. // Log formats a log message as received from service/container
  33. func (l *logConsumer) Log(service, container, message string) {
  34. if l.ctx.Err() != nil {
  35. return
  36. }
  37. cf := l.getColorFunc(service)
  38. prefix := fmt.Sprintf("%-"+strconv.Itoa(l.width)+"s |", container)
  39. for _, line := range strings.Split(message, "\n") {
  40. buf := bytes.NewBufferString(fmt.Sprintf("%s %s\n", cf(prefix), line))
  41. l.writer.Write(buf.Bytes()) // nolint:errcheck
  42. }
  43. }
  44. func (l *logConsumer) Status(service, container, msg string) {
  45. cf := l.getColorFunc(service)
  46. buf := bytes.NewBufferString(cf(fmt.Sprintf("%s %s\n", container, msg)))
  47. l.writer.Write(buf.Bytes()) // nolint:errcheck
  48. }
  49. func (l *logConsumer) getColorFunc(service string) colorFunc {
  50. cf, ok := l.colors[service]
  51. if !ok {
  52. cf = <-loop
  53. l.colors[service] = cf
  54. l.computeWidth()
  55. }
  56. return cf
  57. }
  58. func (l *logConsumer) computeWidth() {
  59. width := 0
  60. for n := range l.colors {
  61. if len(n) > width {
  62. width = len(n)
  63. }
  64. }
  65. l.width = width + 3
  66. }
  67. // LogConsumer consume logs from services and format them
  68. type logConsumer struct {
  69. ctx context.Context
  70. colors map[string]colorFunc
  71. width int
  72. writer io.Writer
  73. }