logs.go 2.0 KB

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