logs.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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. )
  22. func (b *ecsAPIService) Logs(ctx context.Context, project string, w io.Writer) error {
  23. consumer := logConsumer{
  24. colors: map[string]colorFunc{},
  25. width: 0,
  26. writer: w,
  27. }
  28. err := b.SDK.GetLogs(ctx, project, consumer.Log)
  29. return err
  30. }
  31. func (l *logConsumer) Log(service, container, message string) {
  32. cf, ok := l.colors[service]
  33. if !ok {
  34. cf = <-loop
  35. l.colors[service] = cf
  36. l.computeWidth()
  37. }
  38. prefix := fmt.Sprintf("%-"+strconv.Itoa(l.width)+"s |", service)
  39. for _, line := range strings.Split(message, "\n") {
  40. buf := bytes.NewBufferString(fmt.Sprintf("%s %s\n", cf(prefix), line))
  41. l.writer.Write(buf.Bytes()) // nolint:errcheck
  42. }
  43. }
  44. func (l *logConsumer) computeWidth() {
  45. width := 0
  46. for n := range l.colors {
  47. if len(n) > width {
  48. width = len(n)
  49. }
  50. }
  51. l.width = width + 3
  52. }
  53. type logConsumer struct {
  54. colors map[string]colorFunc
  55. width int
  56. writer io.Writer
  57. }