go-docker客户端获取容器日志每秒都不返回

时间:2018-05-22 10:20:38

标签: docker go

我使用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...

诀窍是主方法执行需要一段时间,我想每秒向用户显示容器日志。 我的想法是开始一个新的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()。格式(time.RFC3339)

我在想什么?

1 个答案:

答案 0 :(得分:1)

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

诀窍在于我正在使用&#34; Docker Machine &#34;在笔记本电脑上,我每晚都关闭我的笔记本电脑。每当笔记本电脑进入睡眠状态时,Docker Machine的内部时钟就会冻结。

当笔记本电脑从睡眠状态唤醒时,会导致笔记本电脑时钟和Docker Machine的时钟之间出现时间偏差,而我的Docker Machine则延迟了x个小时。

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

docker-machine restart

之后一切正常