同一主机上运行的多个容器的日志记录解决方案

标签 logging docker

目前我们正在将所有应用程序日志从多个容器重定向到标准输出,并通过主机中的 rsyslog 收集/var/log/message 到 ELK 堆栈。

所有 docker 容器日志都显示为 docker/xxxxxxxx,我们无法判断该日志是针对哪个应用程序的,无论如何我们可以轻松地将应用程序与来自 d​​ocker 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/

相关文章:

python - logging.info 不会出现在控制台上,但会出现警告和错误

Apache httpd 访问日志或 tomcat 访问日志

java - 在 Apache 服务器中维护日志文件

php7-fpm 错误 : failed to retrieve TCP_INFO for socket: Protocol not available (92)

docker - 不允许使用Docker CentOS systemctl

python - Azure 应用服务上的 FastAPI-Docker 镜像引发 [CRITICAL] 工作超时

windows - 尽管设置ImagePullPolicy = Never,但仍无法使用kubectl和minikube启动pod

c++ - 针对 Boost.Log 的 g++ 静态链接错误

c# - 使用 log4net 在运行时读取并记录 HttpSession 数据

docker nginx代理nginx connect()失败(111 : Connection refused) while connecting to upstream