gpt4 book ai didi

docker - go-docker 客户端每秒钟获取容器日志不返回任何内容

转载 作者:IT王子 更新时间:2023-10-29 02:09:48 26 4
gpt4 key购买 nike

我正在使用 docker.io/go-docker 包来启动带有 GO 的容器。一旦容器的主要方法返回,我就能够获取容器的所有日志

if err := cli.ContainerStart(context.Background(), resp.ID, types.ContainerStartOptions{}); err != nil {
panic(err)
}

statusCh, errCh = cli.ContainerWait(context.Background(), resp.ID, container.WaitConditionNotRunning)

select {
case err := <-errCh:
if err != nil {
panic(err)
}
case <-statusCh:
}

out, err := cli.ContainerLogs(context.Background(), resp.ID, types.ContainerLogsOptions{ShowStdout: true, ShowStderr: true})
if err != nil {
panic(err)
}
// Do something with the logs here...

诀窍是 main 方法的执行需要一段时间,我想每秒向用户显示一次容器日志。我的想法是启动一个新的 goroutine 来循环并在 cli.ContainerLogs 上发出请求。

所以我将我的实现更改为:

nowUTC := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)

if err := cli.ContainerStart(context.Background(), resp.ID, types.ContainerStartOptions{}); err != nil {
panic(err)
}

statusCh, errCh = cli.ContainerWait(context.Background(), resp.ID, container.WaitConditionNotRunning)

exitCh := make(chan bool)

go func(since string, exit chan bool) {

Loop:

for {
select {
case <-exit:
break Loop
default:

sinceReq := since
time.Sleep(time.Second)
since = strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
out, err := cli.ContainerLogs(context.Background(), resp.ID, types.ContainerLogsOptions{Since: sinceReq, ShowStdout: true, ShowStderr: true})
if err != nil {
panic(err)
}

b, err := ioutil.ReadAll(out)
if err != nil {
panic(err)
}
log.Printf("Rolling log Contener \n%s", string(b))
// Do something with the logs here...
}
}
}(nowUTC, exitCh)


select {
case err := <-errCh:
exitCh <- true
if err != nil {
panic(err)
}
case <-statusCh:
exitCh <- true
}

一切正常,除了 ioutil.ReadAll(out) 什么都不返回。

我试过多次使用类似的时间格式还是没有任何结果:

  • nowUTC := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
  • nowUTC := strconv.FormatInt(time.Now().UTC().Unix(), 10)
  • nowUTC := strconv.FormatInt(time.Now().UnixNano(), 10)
  • nowUTC := strconv.FormatInt(time.Now().Unix(), 10)
  • nowUTC := time.Now().Format(time.RFC3339)

我错过了什么?

最佳答案

最后,我使用 nowUTC :=time.Now().UTC() 使其正常工作,但问题不仅在于使用的时间格式。

诀窍是我在笔记本电脑上使用“Docker Machine”并且我每晚都关闭我的笔记本电脑。每当笔记本电脑进入休眠状态时,Docker Machine 的内部时钟就会卡住。

当笔记本电脑从 sleep 中醒来时,会导致笔记本电脑时钟和 Docker Machine 时钟之间出现时间漂移,而我的 Docker Machine 晚了 x 小时。

我的 Go 代码在我的笔记本电脑上运行到 CLI 应用程序,并且提取日志的请求的时间标准与日志内容不匹配。

docker-machine restart 后一切正常

关于docker - go-docker 客户端每秒钟获取容器日志不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50465273/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com