logs.go 1.0 KB

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