logs.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. // LogsCommand fetches and shows logs of a container
  15. func LogsCommand() *cobra.Command {
  16. var opts logsOpts
  17. cmd := &cobra.Command{
  18. Use: "logs",
  19. Short: "Fetch the logs of a container",
  20. Args: cobra.ExactArgs(1),
  21. RunE: func(cmd *cobra.Command, args []string) error {
  22. return runLogs(cmd.Context(), args[0], opts)
  23. },
  24. }
  25. cmd.Flags().BoolVarP(&opts.Follow, "follow", "f", false, "Follow log outut")
  26. cmd.Flags().StringVar(&opts.Tail, "tail", "all", "Number of lines to show from the end of the logs")
  27. return cmd
  28. }
  29. func runLogs(ctx context.Context, containerName string, opts logsOpts) error {
  30. c, err := client.New(ctx)
  31. if err != nil {
  32. return errors.Wrap(err, "cannot connect to backend")
  33. }
  34. req := containers.LogsRequest{
  35. Follow: opts.Follow,
  36. Tail: opts.Tail,
  37. Writer: os.Stdout,
  38. }
  39. return c.ContainerService().Logs(ctx, containerName, req)
  40. }