logs.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. Copyright 2020 Docker, Inc.
  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 cmd
  14. import (
  15. "context"
  16. "io"
  17. "os"
  18. "github.com/containerd/console"
  19. "github.com/pkg/errors"
  20. "github.com/spf13/cobra"
  21. "github.com/docker/compose-cli/client"
  22. "github.com/docker/compose-cli/containers"
  23. )
  24. type logsOpts struct {
  25. Follow bool
  26. Tail string
  27. }
  28. // LogsCommand fetches and shows logs of a container
  29. func LogsCommand() *cobra.Command {
  30. var opts logsOpts
  31. cmd := &cobra.Command{
  32. Use: "logs",
  33. Short: "Fetch the logs of a container",
  34. Args: cobra.ExactArgs(1),
  35. RunE: func(cmd *cobra.Command, args []string) error {
  36. return runLogs(cmd.Context(), args[0], opts)
  37. },
  38. }
  39. cmd.Flags().BoolVarP(&opts.Follow, "follow", "f", false, "Follow log outut")
  40. cmd.Flags().StringVar(&opts.Tail, "tail", "all", "Number of lines to show from the end of the logs")
  41. return cmd
  42. }
  43. func runLogs(ctx context.Context, containerName string, opts logsOpts) error {
  44. c, err := client.New(ctx)
  45. if err != nil {
  46. return errors.Wrap(err, "cannot connect to backend")
  47. }
  48. req := containers.LogsRequest{
  49. Follow: opts.Follow,
  50. Tail: opts.Tail,
  51. }
  52. var con io.Writer = os.Stdout
  53. if c, err := console.ConsoleFromFile(os.Stdout); err == nil {
  54. size, err := c.Size()
  55. if err != nil {
  56. return err
  57. }
  58. req.Width = int(size.Width)
  59. con = c
  60. }
  61. req.Writer = con
  62. return c.ContainerService().Logs(ctx, containerName, req)
  63. }