logs.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package backend
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "os/signal"
  7. "strconv"
  8. "strings"
  9. "github.com/compose-spec/compose-go/cli"
  10. "github.com/docker/ecs-plugin/pkg/console"
  11. )
  12. func (b *Backend) Logs(ctx context.Context, options cli.ProjectOptions) error {
  13. name := options.Name
  14. if name == "" {
  15. project, err := cli.ProjectFromOptions(&options)
  16. if err != nil {
  17. return err
  18. }
  19. name = project.Name
  20. }
  21. err := b.api.GetLogs(ctx, name, &logConsumer{
  22. colors: map[string]console.ColorFunc{},
  23. width: 0,
  24. })
  25. if err != nil {
  26. return err
  27. }
  28. signalChan := make(chan os.Signal, 1)
  29. signal.Notify(signalChan, os.Interrupt)
  30. <-signalChan
  31. return nil
  32. }
  33. func (l *logConsumer) Log(service, container, message string) {
  34. cf, ok := l.colors[service]
  35. if !ok {
  36. cf = <-console.Rainbow
  37. l.colors[service] = cf
  38. l.computeWidth()
  39. }
  40. prefix := fmt.Sprintf("%-"+strconv.Itoa(l.width)+"s |", service)
  41. for _, line := range strings.Split(message, "\n") {
  42. fmt.Printf("%s %s\n", cf(prefix), line)
  43. }
  44. }
  45. func (l *logConsumer) computeWidth() {
  46. width := 0
  47. for n := range l.colors {
  48. if len(n) > width {
  49. width = len(n)
  50. }
  51. }
  52. l.width = width + 3
  53. }
  54. type logConsumer struct {
  55. colors map[string]console.ColorFunc
  56. width int
  57. }