logs.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package cmd
  2. import (
  3. "context"
  4. "os"
  5. "github.com/pkg/errors"
  6. "github.com/spf13/cobra"
  7. "github.com/docker/api/client"
  8. "github.com/docker/api/containers"
  9. )
  10. type logsOpts struct {
  11. Follow bool
  12. Tail string
  13. }
  14. func LogsCommand() *cobra.Command {
  15. var opts logsOpts
  16. cmd := &cobra.Command{
  17. Use: "logs",
  18. Short: "Fetch the logs of a container",
  19. Args: cobra.ExactArgs(1),
  20. RunE: func(cmd *cobra.Command, args []string) error {
  21. return runLogs(cmd.Context(), args[0], opts)
  22. },
  23. }
  24. cmd.Flags().BoolVarP(&opts.Follow, "follow", "f", false, "Follow log outut")
  25. cmd.Flags().StringVar(&opts.Tail, "tail", "all", "Number of lines to show from the end of the logs")
  26. return cmd
  27. }
  28. func runLogs(ctx context.Context, containerName string, opts logsOpts) error {
  29. c, err := client.New(ctx)
  30. if err != nil {
  31. return errors.Wrap(err, "cannot connect to backend")
  32. }
  33. req := containers.LogsRequest{
  34. Follow: opts.Follow,
  35. Tail: opts.Tail,
  36. Writer: os.Stdout,
  37. }
  38. return c.ContainerService().Logs(ctx, containerName, req)
  39. }