3

So I am trying to get the combined output of all the container logs with its container name in a log file docker logs --tail -3 with container name >> logst.log file.

2 Answers2

1

docker logs takes a single command so you would have to run them for each container. I guess I could do something along:

docker ps --format='{{.Names}}' | xargs -P0 -d '\n' -n1 sh -c 'docker logs "$1" | sed "s/^/$1: /"' _
  • docker ps --format='{{.Names}}' - print container names
  • xargs - for input
    • -d '\n' - for each line
    • -P0 - execute in parallel with any count of parallel jobs
      • remove this option if you don't intent to do docker logs --follow
      • it may cause problems, consider adding stdbuf -oL and sed -u to unbuffer the streams
    • -n1 - pass one argument to the underyling process
    • sh -c 'script' _ - execute script for each line with line passed as first positional argument
      • docker logs "$1" - get the logs
      • sed 's/^/$1: /' - prepend the name of the docker name to each log line

But a way better and industrial grade solution would be to forward docker logs to journalctl or other logging solution and use that utility to aggregate and filter logs.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
0

Got it.

for i in docker ps -a -q --format "table {{.ID}}"; do { docker ps -a -q --format "table {{.ID}}\t{{.Names}}\n" | grep "$i" & docker logs --timestamps --tail 1 "$i"; } >> logs.log; done

logs.log is a generic file name.