目前我们正在将所有应用程序日志从多个容器重定向到标准输出,并通过主机中的 rsyslog 收集/var/log/message 到 ELK 堆栈。
所有 docker 容器日志都显示为 docker/xxxxxxxx,我们无法判断该日志是针对哪个应用程序的,无论如何我们可以轻松地将应用程序与来自 docker stdout 的多个容器日志区分开来?
最佳答案
(针对 OS X 的说明,但应该在 Linux 中工作)
似乎没有办法使用 docker 命令执行此操作,但是在 bash 中您可以同时运行多个命令,并且使用 sed
您可以使用容器名称作为前缀.
docker logs -f --tail=30 container1 | sed -e 's/^/[-- containerA1 --]/' &
docker logs -f --tail=30 container2 | sed -e 's/^/[-- containerM2 --]/' &
您将同时看到两个容器的输出。
[-- containerA1 --] :: logging line
[-- containerA1 --] :: logging line
[-- containerM2 --] :: logging line
[-- containerM2 --] :: logging line
[-- containerA1 --] :: logging line
[-- containerA1 --] :: logging line
[-- containerM2 --] :: logging line
[-- containerM2 --] :: logging line
一次性尾随所有容器:
#!/bin/bash
names=$(docker ps --format "{{.Names}}")
echo "tailing $names"
while read -r name
do
# eval to show container name in jobs list
eval "docker logs -f --tail=5 \"$name\" | sed -e \"s/^/[-- $name --] /\" &"
# For Ubuntu 16.04
#eval "docker logs -f --tail=5 \"$name\" |& sed -e \"s/^/[-- $name --] /\" &"
done <<< "$names"
function _exit {
echo
echo "Stopping tails $(jobs -p | tr '\n' ' ')"
echo "..."
# Using `sh -c` so that if some have exited, that error will
# not prevent further tails from being killed.
jobs -p | tr '\n' ' ' | xargs -I % sh -c "kill % || true"
echo "Done"
}
# On ctrl+c, kill all tails started by this script.
trap _exit EXIT
# For Ubuntu 16.04
#trap _exit INT
# Don't exit this script until ctrl+c or all tails exit.
wait
为了阻止它们运行 fg
然后为每个容器按 ctrl+c
。
更新:感谢 @Flo-Woo 对 Ubuntu 16.04 的支持
关于同一主机上运行的多个容器的日志记录解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32076878/