logs.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package backend
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "os"
  8. "os/signal"
  9. "strconv"
  10. "strings"
  11. "github.com/compose-spec/compose-go/cli"
  12. "github.com/docker/ecs-plugin/pkg/console"
  13. )
  14. func (b *Backend) Logs(ctx context.Context, options *cli.ProjectOptions, writer io.Writer) error {
  15. name := options.Name
  16. if name == "" {
  17. project, err := cli.ProjectFromOptions(options)
  18. if err != nil {
  19. return err
  20. }
  21. name = project.Name
  22. }
  23. err := b.api.GetLogs(ctx, name, &logConsumer{
  24. colors: map[string]console.ColorFunc{},
  25. width: 0,
  26. writer: writer,
  27. })
  28. if err != nil {
  29. return err
  30. }
  31. signalChan := make(chan os.Signal, 1)
  32. signal.Notify(signalChan, os.Interrupt)
  33. <-signalChan
  34. return nil
  35. }
  36. func (l *logConsumer) Log(service, container, message string) {
  37. cf, ok := l.colors[service]
  38. if !ok {
  39. cf = <-console.Rainbow
  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())
  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. type logConsumer struct {
  59. colors map[string]console.ColorFunc
  60. width int
  61. writer io.Writer
  62. }