Created
April 29, 2021 19:50
-
-
Save bdragon/a5b403297a82e8a0d53fa5a75f9fac0f to your computer and use it in GitHub Desktop.
Tail kubectl logs from multiple selected pods with colorized output.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -euo pipefail | |
# Tail kubectl logs from multiple selected pods with colorized output. | |
function usage() { | |
local name="$(basename "${BASH_SOURCE[0]}")" | |
echo "Synopsis:" | |
echo -e "\t$name -n NAMESPACE -l SELECTOR [ -- KUBECTL_LOGS_ARGS ]\n" | |
echo "Options:" | |
echo -e "\t-n NAMESPACE\tThe Kubernetes namespace used." | |
echo -e "\t-l SELECTOR\tKubernetes selector expression used to find pods." | |
echo "Usage:" | |
echo -e "\t$name -n production -l name=foo -- --timestamps --tail=10\n" | |
exit 1 | |
} | |
NAMESPACE= | |
SELECTOR= | |
# Ensure OPTIND is properly initialized. | |
OPTIND=1 | |
# Parse program arguments. | |
while getopts ":h?n:l:" opt; do | |
case "$opt" in | |
h|\?) | |
usage | |
;; | |
n) | |
NAMESPACE="$OPTARG" | |
;; | |
l) | |
SELECTOR="$OPTARG" | |
;; | |
esac | |
done | |
shift $(( OPTIND - 1 )) | |
if [ "${1:-}" = "--" ]; then | |
shift | |
fi | |
# Validate program arguments. | |
if [ -z "$NAMESPACE" ] || [ -z "$SELECTOR" ]; then | |
usage | |
fi | |
# Array of process ids of background jobs created by this process. | |
declare -a PIDS | |
# Kill child processes when interrupted. | |
trap 'exit' INT TERM ERR | |
trap 'kill 0' EXIT | |
# Array of ANSI escape codes for colors. | |
declare -a COLORS | |
for color in {31..37}; do | |
COLORS+=("\033[0;${color}m") | |
done | |
for color in {91..96}; do | |
COLORS+=("\033[0;${color}m") | |
done | |
# Number of colors. | |
NCOLORS="${#COLORS[@]}" | |
# Names of pods whose logs we want to follow. | |
PODS=( \ | |
$(kubectl get pod -ojsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' -n "$NAMESPACE" -l "$SELECTOR") \ | |
) | |
# Start tailing each pod in the background with colorized output. | |
for i in ${!PODS[@]}; do | |
if [ $i -ge $NCOLORS ]; then | |
i=$(( $i % $NCOLORS )) | |
fi | |
( kubectl logs "pod/${PODS[i]}" -n "$NAMESPACE" -f $@ \ | |
| awk -v color="${COLORS[i]}" -v pod="${PODS[i]}" '{ printf "%s%s ", color, pod; print }' ) & | |
PIDS+=( $! ) | |
done | |
# Wait for background jobs. | |
wait ${PIDS[@]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment