使用容器名称而不是容器ID保存docker容器日志



使用默认的json文件日志记录驱动程序,有没有一种方法可以用容器名称而不是容器ID来记录旋转docker容器日志?

日志文件名中的容器ID看起来不太可读,这是我想用容器名保存日志的时候吗?

可以使用日志选项配置引擎,以便在日志中包含标签:

# cat /etc/docker/daemon.json 
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3",
"labels": "com.docker.stack.namespace,com.docker.swarm.service.name,environment"
}
}
# docker run --label environment=dev busybox echo hello logs
hello logs
root@vm-11:/etc/docker# docker ps -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
9615c898c2d2        busybox             "echo hello logs"   8 seconds ago       Exited (0) 7 seconds ago                       eloquent_germain
# docker logs --details 961
environment=dev hello logs
# more /var/lib/docker/containers/9615c898c2d2aa7439581e08c2e685f154e4bf2bb9fd5ded0c384da3242c6c9e/9615c898c2d2aa7439581e08c2e685f154e4bf2bb9fd5ded0c384da3242c6c9e-json.log
{"log":"hello logsn","stream":"stdout","attrs":{"environment":"dev"},"time":"2020-09-22T11:12:41.279155826Z"}

在对daemon.json进行更改后,您需要重新加载docker引擎,并且更改仅适用于新创建的容器。对于systemd,使用systemctl reload docker进行重新加载。

要专门传递容器名称(不是标签(,可以传递一个";标签";设置:

# docker run --name test-log-opts --log-opt tag="{{.Name}}/{{.ID}}" busybox echo hello log opts
hello log opts
# docker ps -l
CONTAINER ID        IMAGE               COMMAND                 CREATED             STATUS                     PORTS               NAMES
c201d0a2504a        busybox             "echo hello log opts"   6 seconds ago       Exited (0) 5 seconds ago                       test-log-opts
# docker logs --details c20
tag=test-log-opts%2Fc201d0a2504a hello log opts
# more /var/lib/docker/containers/c201d0a2504addedb2b6785850a83e8931052d0d9778438e9dcc27391f45fec2/c201d0a2504addedb2b6785850a83e8931052d0d9778438e9dcc27391f45fec2-json.log
{"log":"hello log optsn","stream":"stdout","attrs":{"tag":"test-log-opts/c201d0a2504a"},"time":"2020-09-22T11:15:26.998956544Z"}

更多详细信息:

  • JSON日志驱动程序选项:https://docs.docker.com/config/containers/logging/json-file/#options
  • 容器日志标记:https://docs.docker.com/config/containers/logging/log_tags/

相关内容

  • 没有找到相关文章