logs.go 1.7 KB

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