如何在docker PythonAPI中流化日志?

2024-05-20 00:00:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用DockerPythonAPI从Dockerfile构建图像。在

import os
import sys
import os.path
import docker


client = docker.from_env()
try:
    here = os.path.dirname(__file__)
    no_cache = False
    dockerfile = os.path.join(here, 'app', 'nextdir')
    image = client.images.build(path=dockerfile, tag='app:v.2.4', nocache=no_cache, stream=True)

操作成功完成,但是我无法流式传输日志。API说:

Return a blocking generator you can iterate over to retrieve build output as it happens

当stream=True时。在

如何在python中获取这些日志?在


Tags: pathdockernoimportdockerfilebuildclienttrue
3条回答

您可以使用low-levelAPI客户端。build()函数将返回一个生成器,您可以迭代该生成器以获取构建日志的块。在

生成器将生成一个包含JSON对象的字符串,您可以对其调用json.loads(),也可以使用build()函数中的decode=True参数来完成此操作。在

一旦您从生成的字典中获取'stream'键,您可能只需要print()它,但是如果您需要将它发送给记录器,最好逐行执行,因为收到的块将包含多行。在

此类代码的一个选项如下:

from docker import APIClient

client = APIClient(base_url='unix://var/run/docker.sock')

# Build docker image
log.info('Building docker image ...')
streamer = client.build(
    decode=True,
    path=args.path,
    tag=args.tag,
)

for chunk in streamer:
    if 'stream' in chunk:
        for line in chunk['stream'].splitlines():
            log.debug(line)

可以使用docker-py中给出的低级API来流化docker构建日志,如下所示:

        here = os.path.dirname(__file__)
        dockerfile = os.path.join(here, 'app', 'nextdir')
        docker_client = docker.APIClient(base_url='unix://var/run/docker.sock')
        generator = docker_client.build(path=dockerfile, tag='app:v.2.4', rm=True)
        while True:
            try:
                output = generator.__next__
                output = output.strip('\r\n')
                json_output = json.loads(output)
                if 'stream' in json_output:
                    click.echo(json_output['stream'].strip('\n'))
            except StopIteration:
                click.echo("Docker image build complete.")
                break
            except ValueError:
                click.echo("Error parsing output from docker image build: %s" % output)

docs状态。。。在

If you want to get the raw output of the build, use the build() method in the low-level API.

你试过了吗?在

相关问题 更多 >