【问题标题】:go-docker client get container logs every seconds returns nothinggo-docker 客户端每秒获取容器日志不返回任何内容
【发布时间】:2018-11-01 01:55:00
【问题描述】:

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

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...

诀窍是主方法执行需要一段时间,我想每秒钟向用户显示一次容器日志。 我的想法是启动一个新的 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)

我错过了什么?

【问题讨论】:

    标签: docker go


    【解决方案1】:

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

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

    当笔记本电脑从睡眠中唤醒时,会导致笔记本电脑时钟和 Docker 机器的时钟之间出现时间偏移,而我的 Docker 机器迟到了 x 小时。

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

    docker-machine restart 之后一切正常

    【讨论】:

      猜你喜欢
      • 2019-06-05
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      • 2022-09-26
      • 2016-07-14
      相关资源
      最近更新 更多