logs.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package client
  2. import (
  3. "fmt"
  4. "io"
  5. "golang.org/x/net/context"
  6. Cli "github.com/docker/docker/cli"
  7. flag "github.com/docker/docker/pkg/mflag"
  8. "github.com/docker/docker/pkg/stdcopy"
  9. "github.com/docker/engine-api/types"
  10. )
  11. var validDrivers = map[string]bool{
  12. "json-file": true,
  13. "journald": true,
  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"}, Cli.DockerCommands["logs"].Description, 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. details := cmd.Bool([]string{"-details"}, false, "Show extra details provided to logs")
  24. tail := cmd.String([]string{"-tail"}, "all", "Number of lines to show from the end of the logs")
  25. cmd.Require(flag.Exact, 1)
  26. cmd.ParseFlags(args, true)
  27. name := cmd.Arg(0)
  28. ctx := context.Background()
  29. c, err := cli.client.ContainerInspect(ctx, name)
  30. if err != nil {
  31. return err
  32. }
  33. if !validDrivers[c.HostConfig.LogConfig.Type] {
  34. return fmt.Errorf("\"logs\" command is supported only for \"json-file\" and \"journald\" logging drivers (got: %s)", c.HostConfig.LogConfig.Type)
  35. }
  36. options := types.ContainerLogsOptions{
  37. ShowStdout: true,
  38. ShowStderr: true,
  39. Since: *since,
  40. Timestamps: *times,
  41. Follow: *follow,
  42. Tail: *tail,
  43. Details: *details,
  44. }
  45. responseBody, err := cli.client.ContainerLogs(ctx, name, options)
  46. if err != nil {
  47. return err
  48. }
  49. defer responseBody.Close()
  50. if c.Config.Tty {
  51. _, err = io.Copy(cli.out, responseBody)
  52. } else {
  53. _, err = stdcopy.StdCopy(cli.out, cli.err, responseBody)
  54. }
  55. return err
  56. }