logs.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. Copyright 2020 Docker, Inc.
  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 ecs
  14. import (
  15. "bytes"
  16. "context"
  17. "fmt"
  18. "io"
  19. "os"
  20. "os/signal"
  21. "strconv"
  22. "strings"
  23. "github.com/compose-spec/compose-go/cli"
  24. )
  25. func (b *ecsAPIService) Logs(ctx context.Context, options *cli.ProjectOptions, writer io.Writer) error {
  26. name := options.Name
  27. if name == "" {
  28. project, err := cli.ProjectFromOptions(options)
  29. if err != nil {
  30. return err
  31. }
  32. name = project.Name
  33. }
  34. consumer := logConsumer{
  35. colors: map[string]colorFunc{},
  36. width: 0,
  37. writer: writer,
  38. }
  39. err := b.SDK.GetLogs(ctx, name, consumer.Log)
  40. if err != nil {
  41. return err
  42. }
  43. signalChan := make(chan os.Signal, 1)
  44. signal.Notify(signalChan, os.Interrupt)
  45. <-signalChan
  46. return nil
  47. }
  48. func (l *logConsumer) Log(service, container, message string) {
  49. cf, ok := l.colors[service]
  50. if !ok {
  51. cf = <-loop
  52. l.colors[service] = cf
  53. l.computeWidth()
  54. }
  55. prefix := fmt.Sprintf("%-"+strconv.Itoa(l.width)+"s |", service)
  56. for _, line := range strings.Split(message, "\n") {
  57. buf := bytes.NewBufferString(fmt.Sprintf("%s %s\n", cf(prefix), line))
  58. l.writer.Write(buf.Bytes()) // nolint:errcheck
  59. }
  60. }
  61. func (l *logConsumer) computeWidth() {
  62. width := 0
  63. for n := range l.colors {
  64. if len(n) > width {
  65. width = len(n)
  66. }
  67. }
  68. l.width = width + 3
  69. }
  70. type logConsumer struct {
  71. colors map[string]colorFunc
  72. width int
  73. writer io.Writer
  74. }