package container import ( "context" "errors" "io" "strconv" "github.com/moby/moby/api/pkg/stdcopy" "github.com/moby/moby/client" ) // ErrNotRunning reports a container that exists but has stopped. var ErrNotRunning = errors.New("container is not running") // FollowLogs streams a running container's stdout and stderr, merged, from // its recent past onward. It is read-only: nothing the caller does reaches // the container. Closing the reader ends the follow. func FollowLogs(ctx context.Context, cli *client.Client, name string, tail int) (io.ReadCloser, error) { inspected, err := cli.ContainerInspect(ctx, name, client.ContainerInspectOptions{}) if err != nil { return nil, err } if inspected.Container.State == nil || !inspected.Container.State.Running { return nil, ErrNotRunning } logs, err := cli.ContainerLogs(ctx, inspected.Container.ID, client.ContainerLogsOptions{ ShowStdout: true, ShowStderr: true, Follow: true, Tail: strconv.Itoa(tail), }) if err != nil { return nil, err } pr, pw := io.Pipe() go func() { // A Kit container has no TTY, so the stream is multiplexed. _, err := stdcopy.StdCopy(pw, pw, logs) _ = logs.Close() _ = pw.CloseWithError(err) }() return &logStream{PipeReader: pr, logs: logs}, nil } type logStream struct { *io.PipeReader logs io.ReadCloser } func (s *logStream) Close() error { return errors.Join(s.PipeReader.Close(), s.logs.Close()) }