github.com/ali-iotechsys/cli@v20.10.0+incompatible/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:37Z) 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:37Z) 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.StringVarP(&opts.tail, "tail", "n", "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  	c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
    54  	if err != nil {
    55  		return err
    56  	}
    57  
    58  	options := types.ContainerLogsOptions{
    59  		ShowStdout: true,
    60  		ShowStderr: true,
    61  		Since:      opts.since,
    62  		Until:      opts.until,
    63  		Timestamps: opts.timestamps,
    64  		Follow:     opts.follow,
    65  		Tail:       opts.tail,
    66  		Details:    opts.details,
    67  	}
    68  	responseBody, err := dockerCli.Client().ContainerLogs(ctx, c.ID, options)
    69  	if err != nil {
    70  		return err
    71  	}
    72  	defer responseBody.Close()
    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  }