github.com/torfuzx/docker@v1.8.1/api/client/logs.go (about)

     1  package client
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/url"
     7  	"time"
     8  
     9  	"github.com/docker/docker/api/types"
    10  	Cli "github.com/docker/docker/cli"
    11  	flag "github.com/docker/docker/pkg/mflag"
    12  	"github.com/docker/docker/pkg/timeutils"
    13  )
    14  
    15  // CmdLogs fetches the logs of a given container.
    16  //
    17  // docker logs [OPTIONS] CONTAINER
    18  func (cli *DockerCli) CmdLogs(args ...string) error {
    19  	cmd := Cli.Subcmd("logs", []string{"CONTAINER"}, "Fetch the logs of a container", true)
    20  	follow := cmd.Bool([]string{"f", "-follow"}, false, "Follow log output")
    21  	since := cmd.String([]string{"-since"}, "", "Show logs since timestamp")
    22  	times := cmd.Bool([]string{"t", "-timestamps"}, false, "Show timestamps")
    23  	tail := cmd.String([]string{"-tail"}, "all", "Number of lines to show from the end of the logs")
    24  	cmd.Require(flag.Exact, 1)
    25  
    26  	cmd.ParseFlags(args, true)
    27  
    28  	name := cmd.Arg(0)
    29  
    30  	serverResp, err := cli.call("GET", "/containers/"+name+"/json", nil, nil)
    31  	if err != nil {
    32  		return err
    33  	}
    34  
    35  	var c types.ContainerJSON
    36  	if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil {
    37  		return err
    38  	}
    39  
    40  	if logType := c.HostConfig.LogConfig.Type; logType != "json-file" {
    41  		return fmt.Errorf("\"logs\" command is supported only for \"json-file\" logging driver (got: %s)", logType)
    42  	}
    43  
    44  	v := url.Values{}
    45  	v.Set("stdout", "1")
    46  	v.Set("stderr", "1")
    47  
    48  	if *since != "" {
    49  		v.Set("since", timeutils.GetTimestamp(*since, time.Now()))
    50  	}
    51  
    52  	if *times {
    53  		v.Set("timestamps", "1")
    54  	}
    55  
    56  	if *follow {
    57  		v.Set("follow", "1")
    58  	}
    59  	v.Set("tail", *tail)
    60  
    61  	sopts := &streamOpts{
    62  		rawTerminal: c.Config.Tty,
    63  		out:         cli.out,
    64  		err:         cli.err,
    65  	}
    66  
    67  	_, err = cli.stream("GET", "/containers/"+name+"/logs?"+v.Encode(), sopts)
    68  	return err
    69  }