Skip to content

Instantly share code, notes, and snippets.

@kare
Last active June 3, 2022 10:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kare/0a1a162670f9ed09a2285641ceaeee39 to your computer and use it in GitHub Desktop.
Save kare/0a1a162670f9ed09a2285641ceaeee39 to your computer and use it in GitHub Desktop.
Tail logs of all Docker containers bash script
#!/bin/bash
set -e -u -o pipefail
function usage() {
local name
name=$(basename "$0")
echo "$name: tail Docker container logs" 1>&2
echo "Usage: $name [-h]" 1>&2
echo " -h Show help" 1>&2
echo "Example: $name" 1>&2
}
while getopts "h" arg; do
case $arg in
h|*) # Show help
usage
exit 1
;;
esac
done
TMPDIR=$(mktemp -d)
# PIDS array contains process id's to kill after this scripts is interrupted by signal INT/QUIT/TERM
PIDS=()
function cleanup() {
trap "" SIGINT SIGQUIT SIGTERM
for pid in "${PIDS[@]}"; do
if ! kill $pid; then
echo "$(basename $0): kill error with pid: $pid" 1>&2
fi
done
rm -rf $TMPDIR
}
function sigint_handler() {
cleanup
exit 130
}
function sigquit_handler() {
cleanup
exit 131
}
function sigterm_handler() {
cleanup
exit 143
}
trap sigint_handler INT
trap sigquit_handler QUIT
trap sigterm_handler TERM
for id in $(docker ps --format="{{.Names}}" -a); do
log=$TMPDIR/$id.log
touch "$log"
docker logs -f "$id" 1> "$log" 2>&1 &
PIDS+=($!)
done
tail -f $TMPDIR/*.{log,err} &
PIDS+=($!)
wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment