github.com/AliyunContainerService/cli@v0.0.0-20181009023821-814ced4b30d0/cli/command/container/logs.go (about)

     1  package container
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  
     7  	"github.com/docker/cli/cli"
     8  	"github.com/docker/cli/cli/command"
     9  	"github.com/docker/docker/api/types"
    10  	"github.com/docker/docker/pkg/stdcopy"
    11  	"github.com/spf13/cobra"
    12  )
    13  
    14  type logsOptions struct {
    15  	follow     bool
    16  	since      string
    17  	until      string
    18  	timestamps bool
    19  	details    bool
    20  	tail       string
    21  
    22  	container string
    23  }
    24  
    25  // NewLogsCommand creates a new cobra.Command for `docker logs`
    26  func NewLogsCommand(dockerCli command.Cli) *cobra.Command {
    27  	var opts logsOptions
    28  
    29  	cmd := &cobra.Command{
    30  		Use:   "logs [OPTIONS] CONTAINER",
    31  		Short: "Fetch the logs of a container",
    32  		Args:  cli.ExactArgs(1),
    33  		RunE: func(cmd *cobra.Command, args []string) error {
    34  			opts.container = args[0]
    35  			return runLogs(dockerCli, &opts)
    36  		},
    37  	}
    38  
    39  	flags := cmd.Flags()
    40  	flags.BoolVarP(&opts.follow, "follow", "f", false, "Follow log output")
    41  	flags.StringVar(&opts.since, "since", "", "Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)")
    42  	flags.StringVar(&opts.until, "until", "", "Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)")
    43  	flags.SetAnnotation("until", "version", []string{"1.35"})
    44  	flags.BoolVarP(&opts.timestamps, "timestamps", "t", false, "Show timestamps")
    45  	flags.BoolVar(&opts.details, "details", false, "Show extra details provided to logs")
    46  	flags.StringVar(&opts.tail, "tail", "all", "Number of lines to show from the end of the logs")
    47  	return cmd
    48  }
    49  
    50  func runLogs(dockerCli command.Cli, opts *logsOptions) error {
    51  	ctx := context.Background()
    52  
    53  	options := types.ContainerLogsOptions{
    54  		ShowStdout: true,
    55  		ShowStderr: true,
    56  		Since:      opts.since,
    57  		Until:      opts.until,
    58  		Timestamps: opts.timestamps,
    59  		Follow:     opts.follow,
    60  		Tail:       opts.tail,
    61  		Details:    opts.details,
    62  	}
    63  	responseBody, err := dockerCli.Client().ContainerLogs(ctx, opts.container, options)
    64  	if err != nil {
    65  		return err
    66  	}
    67  	defer responseBody.Close()
    68  
    69  	c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
    70  	if err != nil {
    71  		return err
    72  	}
    73  
    74  	if c.Config.Tty {
    75  		_, err = io.Copy(dockerCli.Out(), responseBody)
    76  	} else {
    77  		_, err = stdcopy.StdCopy(dockerCli.Out(), dockerCli.Err(), responseBody)
    78  	}
    79  	return err
    80  }