【发布时间】: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)
我错过了什么?
【问题讨论】: