logs.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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/docker/compose/v2/cmd/formatter"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/compose/v2/pkg/api"
  20. )
  21. type logsOptions struct {
  22. *projectOptions
  23. composeOptions
  24. follow bool
  25. tail string
  26. since string
  27. until string
  28. noColor bool
  29. noPrefix bool
  30. timestamps bool
  31. }
  32. func logsCommand(p *projectOptions, backend api.Service) *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: Adapt(func(ctx context.Context, args []string) error {
  40. return runLogs(ctx, backend, opts, args)
  41. }),
  42. ValidArgsFunction: serviceCompletion(p),
  43. }
  44. flags := logsCmd.Flags()
  45. flags.BoolVarP(&opts.follow, "follow", "f", false, "Follow log output.")
  46. flags.StringVar(&opts.since, "since", "", "Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)")
  47. flags.StringVar(&opts.until, "until", "", "Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)")
  48. flags.BoolVar(&opts.noColor, "no-color", false, "Produce monochrome output.")
  49. flags.BoolVar(&opts.noPrefix, "no-log-prefix", false, "Don't print prefix in logs.")
  50. flags.BoolVarP(&opts.timestamps, "timestamps", "t", false, "Show timestamps.")
  51. flags.StringVar(&opts.tail, "tail", "all", "Number of lines to show from the end of the logs for each container.")
  52. return logsCmd
  53. }
  54. func runLogs(ctx context.Context, backend api.Service, opts logsOptions, services []string) error {
  55. projectName, err := opts.toProjectName()
  56. if err != nil {
  57. return err
  58. }
  59. consumer := formatter.NewLogConsumer(ctx, os.Stdout, !opts.noColor, !opts.noPrefix)
  60. return backend.Logs(ctx, projectName, consumer, api.LogOptions{
  61. Services: services,
  62. Follow: opts.follow,
  63. Tail: opts.tail,
  64. Since: opts.since,
  65. Until: opts.until,
  66. Timestamps: opts.timestamps,
  67. })
  68. }