Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ho to write logs in Docker container

Tags:

docker

logging

I made most simple C application which just printing a message:

#include <stdio.h>
#include <unistd.h>
int main(){
    int i = 0;
    while(1) {
        sleep(1);
        printf("sleeping ... %d\n", i++);
    }
}

Then, made a simplest possible Dockerfile for it:

FROM fedora

USER root
WORKDIR /root

ADD sleep-play .

CMD ["/root/sleep-play"]

Then, run that container as simple as it could:

sudo docker build -t sleeping .
sudo docker run --name sleeping -d sleeping

Finally I'm expecting to see my stdout output, but nothing happens:

sudo docker logs -f sleeping
## nothing shown!

From here:

... By default, docker logs shows the command’s STDOUT and STDERR.

What I'm doing wrong?

like image 984
Ivan Talalaev Avatar asked Oct 23 '25 18:10

Ivan Talalaev


1 Answers

I'm not quite sure, my best guess is that printf is buffered and maybe the buffer will not flush automaticly here.

Try to flush it manually:

fflush(stdout)

See also this related Stackoverflow entry for flushing manual printf statements: write() to stdout and printf output not interleaved?

like image 145
snap Avatar answered Oct 26 '25 06:10

snap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!