container_logs.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package client // import "github.com/docker/docker/client"
  2. import (
  3. "context"
  4. "io"
  5. "net/url"
  6. "time"
  7. "github.com/docker/docker/api/types/container"
  8. timetypes "github.com/docker/docker/api/types/time"
  9. "github.com/pkg/errors"
  10. )
  11. // ContainerLogs returns the logs generated by a container in an io.ReadCloser.
  12. // It's up to the caller to close the stream.
  13. //
  14. // The stream format on the response will be in one of two formats:
  15. //
  16. // If the container is using a TTY, there is only a single stream (stdout), and
  17. // data is copied directly from the container output stream, no extra
  18. // multiplexing or headers.
  19. //
  20. // If the container is *not* using a TTY, streams for stdout and stderr are
  21. // multiplexed.
  22. // The format of the multiplexed stream is as follows:
  23. //
  24. // [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}[]byte{OUTPUT}
  25. //
  26. // STREAM_TYPE can be 1 for stdout and 2 for stderr
  27. //
  28. // SIZE1, SIZE2, SIZE3, and SIZE4 are four bytes of uint32 encoded as big endian.
  29. // This is the size of OUTPUT.
  30. //
  31. // You can use github.com/docker/docker/pkg/stdcopy.StdCopy to demultiplex this
  32. // stream.
  33. func (cli *Client) ContainerLogs(ctx context.Context, container string, options container.LogsOptions) (io.ReadCloser, error) {
  34. query := url.Values{}
  35. if options.ShowStdout {
  36. query.Set("stdout", "1")
  37. }
  38. if options.ShowStderr {
  39. query.Set("stderr", "1")
  40. }
  41. if options.Since != "" {
  42. ts, err := timetypes.GetTimestamp(options.Since, time.Now())
  43. if err != nil {
  44. return nil, errors.Wrap(err, `invalid value for "since"`)
  45. }
  46. query.Set("since", ts)
  47. }
  48. if options.Until != "" {
  49. ts, err := timetypes.GetTimestamp(options.Until, time.Now())
  50. if err != nil {
  51. return nil, errors.Wrap(err, `invalid value for "until"`)
  52. }
  53. query.Set("until", ts)
  54. }
  55. if options.Timestamps {
  56. query.Set("timestamps", "1")
  57. }
  58. if options.Details {
  59. query.Set("details", "1")
  60. }
  61. if options.Follow {
  62. query.Set("follow", "1")
  63. }
  64. query.Set("tail", options.Tail)
  65. resp, err := cli.get(ctx, "/containers/"+container+"/logs", query, nil)
  66. if err != nil {
  67. return nil, err
  68. }
  69. return resp.body, nil
  70. }