logs.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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, ok := l.colors[service]
  38. if !ok {
  39. cf = <-loop
  40. l.colors[service] = cf
  41. l.computeWidth()
  42. }
  43. prefix := fmt.Sprintf("%-"+strconv.Itoa(l.width)+"s |", service)
  44. for _, line := range strings.Split(message, "\n") {
  45. buf := bytes.NewBufferString(fmt.Sprintf("%s %s\n", cf(prefix), line))
  46. l.writer.Write(buf.Bytes()) // nolint:errcheck
  47. }
  48. }
  49. func (l *logConsumer) computeWidth() {
  50. width := 0
  51. for n := range l.colors {
  52. if len(n) > width {
  53. width = len(n)
  54. }
  55. }
  56. l.width = width + 3
  57. }
  58. // LogConsumer consume logs from services and format them
  59. type logConsumer struct {
  60. ctx context.Context
  61. colors map[string]colorFunc
  62. width int
  63. writer io.Writer
  64. }