Read docker container logs not working for runing containers - Golang

Viewed 27

I'm using below function to read docker container logs, it works perfectly for exited containers and returns result with logs, but for running containers it's losing execution at below line and never returns result,

_, err := reader.Read(hdr)

what could be problem here, and how it can be fixed?

func ReadContainerLogs(containerID string, since string, until string) (ContainerLog, error) {
    dockerLogs := ContainerLog{ContainerID: containerID}

    options := types.ContainerLogsOptions{
        ShowStdout: true,
        ShowStderr: true,
        Since:      since,
        Until:      until,
        Timestamps: true,
        Follow:     true,
        Tail:       "",
        Details:    false,
    }

    reader, err := dockerClient.ContainerLogs(context.Background(), containerID, options)
    if err != nil {
        return dockerLogs, err
    }
    defer reader.Close()

    hdr := make([]byte, 8)
    for {
        var docLog DockerLog
        _, err := reader.Read(hdr)
        if err != nil {
            if err == io.EOF {
                return dockerLogs, nil
            }

            return dockerLogs, err
        }

        count := binary.BigEndian.Uint32(hdr[4:])
        dat := make([]byte, count)
        _, err = reader.Read(dat)
        if err != nil && err != io.EOF {
            return dockerLogs, err
        }

        time, log, found := strings.Cut(string(dat), " ")
        if found {
            docLog.Time = time
            docLog.Log = log
            switch hdr[0] {
            case 1:
                docLog.Stream = "Stdout"
            default:
                docLog.Stream = "Stderr"
            }

            dockerLogs.DockerLogs = append(dockerLogs.DockerLogs, docLog)
        }
    }
}
1 Answers

It was really very small mistake, I had to set

ContainerLogsOptions{Follow: false}

That resolved the problem

Related