compose/cli/cmd/logs.go

51 lines
1.1 KiB
Go
Raw Normal View History

2020-05-03 13:41:45 +02:00
package cmd
import (
"context"
"os"
"github.com/pkg/errors"
"github.com/spf13/cobra"
2020-05-04 16:38:02 +02:00
"github.com/docker/api/client"
"github.com/docker/api/containers"
2020-05-03 13:41:45 +02:00
)
type logsOpts struct {
Follow bool
2020-05-04 16:38:02 +02:00
Tail string
2020-05-03 13:41:45 +02:00
}
// LogsCommand fetches and shows logs of a container
2020-05-03 13:41:45 +02:00
func LogsCommand() *cobra.Command {
var opts logsOpts
cmd := &cobra.Command{
Use: "logs",
Short: "Fetch the logs of a container",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return runLogs(cmd.Context(), args[0], opts)
},
}
cmd.Flags().BoolVarP(&opts.Follow, "follow", "f", false, "Follow log outut")
2020-05-04 16:38:02 +02:00
cmd.Flags().StringVar(&opts.Tail, "tail", "all", "Number of lines to show from the end of the logs")
2020-05-03 13:41:45 +02:00
return cmd
}
2020-05-04 16:38:02 +02:00
func runLogs(ctx context.Context, containerName string, opts logsOpts) error {
2020-05-03 13:41:45 +02:00
c, err := client.New(ctx)
if err != nil {
return errors.Wrap(err, "cannot connect to backend")
}
2020-05-04 16:38:02 +02:00
req := containers.LogsRequest{
Follow: opts.Follow,
Tail: opts.Tail,
Writer: os.Stdout,
}
return c.ContainerService().Logs(ctx, containerName, req)
2020-05-03 13:41:45 +02:00
}