Journald 日志驱动

journald 日志驱动程序将容器日志发送到 systemd 日志。 日志条目可以通过使用 journalctl 命令、使用 journal API 或使用 docker logs 命令来检索。

除了日志消息本身的文本外,journald 日志驱动程序还会在每条消息的日志中存储以下元数据:

FieldDescription
CONTAINER_IDThe container ID truncated to 12 characters.
CONTAINER_ID_FULLThe full 64-character container ID.
CONTAINER_NAMEThe container name at the time it was started. If you use docker rename to rename a container, the new name isn't reflected in the journal entries.
CONTAINER_TAG, SYSLOG_IDENTIFIERThe container tag ( 日志标签选项文档).
CONTAINER_PARTIAL_MESSAGEA field that flags log integrity. Improve logging of long log lines.
IMAGE_NAMEThe name of the container image.

用法

要将journald驱动程序设置为默认的日志记录驱动程序,请在daemon.json文件中将log-driverlog-opts键设置为适当的值,该文件位于Linux主机上的/etc/docker/或Windows Server上的C:\ProgramData\docker\config\daemon.json。有关使用daemon.json配置Docker的更多信息,请参阅daemon.json

以下示例将日志驱动程序设置为 journald

{
  "log-driver": "journald"
}

重启Docker以使更改生效。

要为特定容器配置日志驱动程序,请在docker run命令上使用--log-driver标志。

$ docker run --log-driver=journald ...

选项

使用 --log-opt NAME=VALUE 标志来指定额外的 journald 日志驱动选项。

OptionRequiredDescription
tagoptionalSpecify template to set CONTAINER_TAG and SYSLOG_IDENTIFIER value in journald logs. Refer to 日志标签选项文档 to customize the log tag format.
labelsoptionalComma-separated list of keys of labels, which should be included in message, if these labels are specified for the container.
labels-regexoptionalSimilar to and compatible with labels. A regular expression to match logging-related labels. Used for advanced  日志标签选项.
envoptionalComma-separated list of keys of environment variables, which should be included in message, if these variables are specified for the container.
env-regexoptionalSimilar to and compatible with env. A regular expression to match logging-related environment variables. Used for advanced  日志标签选项.

如果labelenv选项之间发生冲突,env的值将优先。每个选项都会向日志消息的属性添加额外的字段。

以下是记录到journald所需的日志选项示例。

$ docker run \
    --log-driver=journald \
    --log-opt labels=location \
    --log-opt env=TEST \
    --env "TEST=false" \
    --label location=west \
    your/application

此配置还指示驱动程序在有效负载中包含标签位置和环境变量TEST。如果省略了--env "TEST=false"--label location=west参数,则相应的键将不会在journald日志中设置。

关于容器名称的说明

记录在CONTAINER_NAME字段中的值是启动时设置的容器名称。如果您使用docker rename来重命名容器,新名称不会反映在日志条目中。日志条目继续使用原始名称。

使用journalctl检索日志消息

使用journalctl命令检索日志消息。您可以应用过滤表达式来限制检索到的消息,使其仅与特定容器相关联:

$ sudo journalctl CONTAINER_NAME=webserver

您可以使用额外的过滤器来进一步限制检索到的消息。-b标志仅检索自上次系统启动以来生成的消息:

$ sudo journalctl -b CONTAINER_NAME=webserver

-o 标志指定检索日志消息的格式。使用 -o json 以 JSON 格式返回日志消息。

$ sudo journalctl -o json CONTAINER_NAME=webserver

查看启用了TTY的容器的日志

如果在容器上启用了TTY,您可能会在检索日志消息时在输出中看到[10B blob data]。 原因是\r被附加到行尾,而journalctl不会自动删除它,除非设置了--all

$ sudo journalctl -b CONTAINER_NAME=webserver --all

使用 journal API 检索日志消息

此示例使用 systemd Python 模块来检索容器日志:

import systemd.journal

reader = systemd.journal.Reader()
reader.add_match('CONTAINER_NAME=web')

for msg in reader:
    print '{CONTAINER_ID_FULL}: {MESSAGE}'.format(**msg)