1
0

logs.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 compose
  14. import (
  15. "context"
  16. "os"
  17. "github.com/spf13/cobra"
  18. "github.com/docker/compose-cli/api/compose"
  19. "github.com/docker/compose-cli/api/context/store"
  20. "github.com/docker/compose-cli/cli/formatter"
  21. )
  22. type logsOptions struct {
  23. *projectOptions
  24. composeOptions
  25. follow bool
  26. tail string
  27. noColor bool
  28. noPrefix bool
  29. timestamps bool
  30. }
  31. func logsCommand(p *projectOptions, contextType string, backend compose.Service) *cobra.Command {
  32. opts := logsOptions{
  33. projectOptions: p,
  34. }
  35. logsCmd := &cobra.Command{
  36. Use: "logs [service...]",
  37. Short: "View output from containers",
  38. RunE: Adapt(func(ctx context.Context, args []string) error {
  39. return runLogs(ctx, backend, opts, args)
  40. }),
  41. }
  42. flags := logsCmd.Flags()
  43. flags.BoolVarP(&opts.follow, "follow", "f", false, "Follow log output.")
  44. flags.BoolVar(&opts.noColor, "no-color", false, "Produce monochrome output.")
  45. flags.BoolVar(&opts.noPrefix, "no-log-prefix", false, "Don't print prefix in logs.")
  46. flags.BoolVarP(&opts.timestamps, "timestamps", "t", false, "Show timestamps.")
  47. if contextType == store.DefaultContextType {
  48. flags.StringVar(&opts.tail, "tail", "all", "Number of lines to show from the end of the logs for each container.")
  49. }
  50. return logsCmd
  51. }
  52. func runLogs(ctx context.Context, backend compose.Service, opts logsOptions, services []string) error {
  53. projectName, err := opts.toProjectName()
  54. if err != nil {
  55. return err
  56. }
  57. consumer := formatter.NewLogConsumer(ctx, os.Stdout, !opts.noColor, !opts.noPrefix)
  58. return backend.Logs(ctx, projectName, consumer, compose.LogOptions{
  59. Services: services,
  60. Follow: opts.follow,
  61. Tail: opts.tail,
  62. Timestamps: opts.timestamps,
  63. })
  64. }