GoLang将STDOUT和STDERR写入log15文件

时间:2018-08-06 14:17:13

标签: go logging

我有GoLang Application,在其中我使用log15将日志写入文件。我用于log15的软件包是gopkg.in/inconshreveable/log15.v2,遇到了一种情况,我想将STDERR和STDOUT的信息写入到我写log15日志的同一文件中。有没有可能实现相同目标的方法

2 个答案:

答案 0 :(得分:1)

您可以使用管道捕获os.Stdout,然后使用io.MultiWriter

将输出重定向到实际的标准输出和文件。
f, _ := os.OpenFile("my.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0664)
multiWriter := io.MultiWriter(os.Stdout, f)
rd, wr, err := os.Pipe()
if err != nil {
    os.Exit(1)
}

// overwrite os.Stdout
os.Stdout = wr

go func() {
    scanner := bufio.NewScanner(rd)
    for scanner.Scan() {
        stdoutLine := scanner.Text()
        multiWriter.Write([]byte(stdoutLine + "\n"))
    }
}()


fmt.Println("foobar")

// hacky sleep to ensure the go routine can write before program exits
time.Sleep(time.Second) 

您当然可以使用os.Stderr来应用

尽管您必须找到如何在log15文件上获取句柄,但这应该不会太困难

使用此方法可能会遇到的问题是,无法保证goroutine在程序结束时会执行其工作(请参见sleep hack),不确定如何实现

答案 1 :(得分:0)

用于创建用于记录stderr或stdout数据的日志文件。使用OpenFile创建一个文件,然后按SetOutput的格式创建文件。

f, err := os.OpenFile("EDUC_LOG", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664)

if err != nil {
    panic(err)
}

defer f.Close()

log.SetOutput(f)

每当您尝试记录一些值(例如出现错误为

)时,这会将输出打印到日志文件中
if err != nil{
       log.Println(err) // this will create a file if not created to output the log in a file.
}

已编辑:

致命错误将在stdout而不是文件上输出输出,因为程序将在向文件写入任何内容之前退出。

package main

import (
    "log"
)

func main() {
    log.Println("error1")
    log.Fatal("error1")
    log.Println("error2") // this will not print since the program will exit the main with fatal error
}

Playground Example