Golang - 将Exec输出复制到日志 [英] Golang - Copy Exec output to Log

查看:196
本文介绍了Golang - 将Exec输出复制到日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想及时将进程的输出重定向到 log 。我可以做到这一点,如果我等待过程完成这样的:

  cmd:= exec.Command(yes, Go is awesome)//打印Go is awesome,永远
out,err:= cmd.CombinedOutput()
log.Printf(%s,out)

但是,如果这个过程需要很长时间或者没有完成,那么这个过程不太有用。我知道我可以像这样实时写入stdout:

$ p code> cmd:= exec.Command(yes)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()

尽管如此,这并不能真正帮助我,因为我正在写一个不写入终端的服务。我正在寻找一些能够让我做这样的事情:

  cmd:= exec.Command(yes)
cmd.Stdout = log.Stdout
cmd.Stderr = log.Stdout
cmd.Run()

log 不能直接访问其编写器,所以这是不可能的。当然,我不是唯一的这个问题,这通常是如何做到的? 你应该使用 pipe ,例如:

 stdout,err:= cmd.StdoutPipe()
if err!= nil {
return 0,err
}

//在设置管道后启动命令
if err:= cmd.Start(); err!= nil {
return 0,err
}

//读取命令的标准输出行
in:= bufio.NewScanner(stdout)

for inScan(){
log.Printf(in.Text())//将每行写入您的日志,或者您需要的任何内容
}
if err := in.Err(); err!= nil {
log.Printf(error:%s,err)
}

我在这里只处理了 Stdout ,但可以同时处理 Stderr ,例如通过使用goroutine。


I would like to redirect the output of a process to log in a timely manner. I can do it if I wait for the process to finish like this:

cmd := exec.Command("yes", "Go is awesome") // Prints "Go is awesome", forever 
out, err := cmd.CombinedOutput()
log.Printf("%s", out)

However, if the process takes a long time or doesn't finish this is less useful. I know I can write to stdout in real time like this:

cmd := exec.Command("yes")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()

This doesn't really help me though, because I am writing a service that isn't writing to a terminal. I'm looking for something that will let me do something like:

cmd := exec.Command("yes")
cmd.Stdout = log.Stdout
cmd.Stderr = log.Stdout
cmd.Run()

log doesn't give direct access to its writer so this is not possible. Surely I'm not the only with this problem, how is this typically done?

解决方案

You should use a pipe here, for example:

stdout, err := cmd.StdoutPipe()
if err != nil {
    return 0, err
}

// start the command after having set up the pipe
if err := cmd.Start(); err != nil {
    return 0, err
}

// read command's stdout line by line
in := bufio.NewScanner(stdout)

for in.Scan() {
    log.Printf(in.Text()) // write each line to your log, or anything you need
}
if err := in.Err(); err != nil {
    log.Printf("error: %s", err)
}

I have only handled Stdout here, but it is possible to handle Stderr at the same time, for example by using a goroutine.

这篇关于Golang - 将Exec输出复制到日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆