docker-py icon indicating copy to clipboard operation
docker-py copied to clipboard

Container log return a single character instead line

Open moti-malka opened this issue 4 years ago • 3 comments

I try to get container logs using stream but instead of getting a line every time I get a single character For example: If the line in log is: 172.17.0.1 - - [17 / Nov / 2021: 14: 54: 05 +0000] "GET / HTTP / 1.1" 304 0 "-"

So I get in output 1 and in the next log I get the next character 7

Here is my python code:

container_logs = Sdk.docker_client.logs(container=containerid,
                                            stdout=True,
                                            stream=True)
while True:
        try:
            log = next(container_logs).decode("utf-8")
            socketio.emit('stream_logs_response', {'log': log, 'containerid':containerid}, to=sessionid)
            socketio.sleep(0)
       except StopIteration:
            socketio.emit('stream_logs_response', {'log': 'CONTAINER NOT RUNNING','containerid':containerid }, to=room)
            break

what am I missing here?

moti-malka avatar Nov 17 '21 15:11 moti-malka

@shmuel-raichman ++

moti-malka avatar Nov 17 '21 15:11 moti-malka

@moti-malka maybe try using attach instead.

From the documentation:

attach(container, stdout=True, stderr=True, stream=False, logs=False, demux=False) Attach to a container.

The .logs() function is a wrapper around this method, which you can use instead if you want to fetch/stream container output without first retrieving the entire backlog.

This function not includes all of the logs function but maybe it will be enough for our use case?

shmuel-raichman avatar Nov 17 '21 16:11 shmuel-raichman

I faced the same issue. According to the code of APIClient._get_result_tty, this happens when you started the container with tty=True. In this case, logs(stream=True) function emits events chunked to separate bytes. It's not well documented.

mouchar avatar Feb 26 '22 18:02 mouchar

This was my hacky work around since the chars are coming in 1 char at a time

line = ""
for char in container.logs(stream=True, follow=True):
    char = char.decode("utf-8")
    line += char
    if char == "\n":
        line = line.strip()
        print(line)
        line = ""

kyrlon avatar Feb 28 '23 14:02 kyrlon