logs.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. noColor bool
  29. noPrefix bool
  30. timestamps bool
  31. }
  32. func logsCommand(p *projectOptions, contextType string) *cobra.Command {
  33. opts := logsOptions{
  34. projectOptions: p,
  35. }
  36. logsCmd := &cobra.Command{
  37. Use: "logs [service...]",
  38. Short: "View output from containers",
  39. RunE: func(cmd *cobra.Command, args []string) error {
  40. return runLogs(cmd.Context(), opts, args)
  41. },
  42. }
  43. flags := logsCmd.Flags()
  44. flags.BoolVar(&opts.follow, "follow", false, "Follow log output.")
  45. flags.BoolVar(&opts.noColor, "no-color", false, "Produce monochrome output.")
  46. flags.BoolVar(&opts.noPrefix, "no-log-prefix", false, "Don't print prefix in logs.")
  47. flags.BoolVarP(&opts.timestamps, "timestamps", "t", false, "Show timestamps.")
  48. if contextType == store.DefaultContextType {
  49. flags.StringVar(&opts.tail, "tail", "all", "Number of lines to show from the end of the logs for each container.")
  50. }
  51. return logsCmd
  52. }
  53. func runLogs(ctx context.Context, opts logsOptions, services []string) error {
  54. c, err := client.NewWithDefaultLocalBackend(ctx)
  55. if err != nil {
  56. return err
  57. }
  58. projectName, err := opts.toProjectName()
  59. if err != nil {
  60. return err
  61. }
  62. consumer := formatter.NewLogConsumer(ctx, os.Stdout, !opts.noColor, !opts.noPrefix)
  63. return c.ComposeService().Logs(ctx, projectName, consumer, compose.LogOptions{
  64. Services: services,
  65. Follow: opts.follow,
  66. Tail: opts.tail,
  67. Timestamps: opts.timestamps,
  68. })
  69. }