logs.go 1.6 KB

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