英文:
pipe data from kubectl command to terminal in go
问题
我正在创建一个命令行界面(CLI),我想要做的是将 gcloud 命令的输出导入到正在执行的终端中。
例如,一个人可能会运行以下命令:$ cli <MICRO_SERVICE> --branch staging --tail 1000 --since 2022-04-20T15:39:00Z
以下是我为代码编写的部分:
logsFormat := fmt.Sprintf("kubectl logs -n <NAME_SPACE> --container=%s -f --timestamps=true --since-time=%s --tail %d -l app=%s", app, since, tail, app)
logsCmd := exec.Command("bash", "-c", logsFormat)
logsstderr, err := logsCmd.StderrPipe()
if err != nil {
log.Fatal(err)
}
if err = logsCmd.Start(); err != nil {
log.Fatal(err)
}
defer logsCmd.Wait()
go io.Copy(os.Stdout, logsstderr)
当我运行该命令时,kubectl
没有报错,但我看不到来自该微服务的日志。我怀疑我没有正确地将从 kubectl
返回的数据导入到终端中。
英文:
I am creating a CLI, what I am trying to do is to pipe the output of the gcloud command to the terminal where it's being executed.
for example one might do the command $ cli <MICRO_SERVICE> --branch staging --tail 1000 --since 2022-04-20T15:39:00Z
this is what I have written for the code:
logsFormat := fmt.Sprintf("kubectl logs -n <NAME_SPACE> --container=%s -f --timestamps=true --since-time=%s --tail %d -l app=%s", app, since, tail, app)
logsCmd := exec.Command("bash", "-c", logsFormat)
logsstderr, err := logsCmd.StderrPipe()
if err != nil {
log.Fatal(err)
}
if err = logsCmd.Start(); err != nil {
log.Fatal(err)
}
defer logsCmd.Wait()
go io.Copy(os.Stdout, logsstderr)
when I run the command I get no errors from kubectl
but I don't see the logs from that microservice. What I suspect is that I am missing the proper way of piping the data being returned from kubectl
to the terminal
答案1
得分: 1
我将其更新为:
logsFormat := fmt.Sprintf("kubectl logs -n <NAME_SPACE> --container=%s -f --timestamps=true --since-time=%s --tail %d -l app=%s", app, since, tail, app)
logsCmd := exec.Command("bash", "-c", logsFormat)
stdOut, err := logsCmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
err = logsCmd.Start()
if err != nil {
log.Fatal(err)
}
buf := bufio.NewReader(stdOut)
for {
line, _, err := buf.ReadLine()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(line))
}
使用 buf := bufio.NewReader(stdOut)
是主要的更改。
英文:
I updated it to:
logsFormat := fmt.Sprintf("kubectl logs -n <NAME_SPACE> --container=%s -f --timestamps=true --since-time=%s --tail %d -l app=%s", app, since, tail, app)
logsCmd := exec.Command("bash", "-c", logsFormat)
stdOut, err := logsCmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
err = logsCmd.Start()
if err != nil {
log.Fatal(err)
}
buf := bufio.NewReader(stdOut)
for {
line, _, err := buf.ReadLine()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(line))
}
using buf := bufio.NewReader(stdOut)
was the main change
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论