logs.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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/client"
  19. "github.com/docker/compose-cli/api/compose"
  20. "github.com/docker/compose-cli/api/context/store"
  21. "github.com/docker/compose-cli/cli/formatter"
  22. )
  23. type logsOptions struct {
  24. *projectOptions
  25. composeOptions
  26. follow bool
  27. tail string
  28. }
  29. func logsCommand(p *projectOptions, contextType string) *cobra.Command {
  30. opts := logsOptions{
  31. projectOptions: p,
  32. }
  33. logsCmd := &cobra.Command{
  34. Use: "logs [service...]",
  35. Short: "View output from containers",
  36. RunE: func(cmd *cobra.Command, args []string) error {
  37. return runLogs(cmd.Context(), opts, args)
  38. },
  39. }
  40. logsCmd.Flags().BoolVar(&opts.follow, "follow", false, "Follow log output.")
  41. if contextType == store.DefaultContextType {
  42. logsCmd.Flags().StringVar(&opts.tail, "tail", "all", "Number of lines to show from the end of the logs for each container.")
  43. }
  44. return logsCmd
  45. }
  46. func runLogs(ctx context.Context, opts logsOptions, services []string) error {
  47. c, err := client.NewWithDefaultLocalBackend(ctx)
  48. if err != nil {
  49. return err
  50. }
  51. projectName, err := opts.toProjectName()
  52. if err != nil {
  53. return err
  54. }
  55. consumer := formatter.NewLogConsumer(ctx, os.Stdout)
  56. return c.ComposeService().Logs(ctx, projectName, consumer, compose.LogOptions{
  57. Services: services,
  58. Follow: opts.follow,
  59. Tail: opts.tail,
  60. })
  61. }