gpt4 book ai didi

go - 将 Golang 日志输出设置为文件不会在函数声明之外持续存在

转载 作者:IT王子 更新时间:2023-10-29 02:35:48 36 4
gpt4 key购买 nike

我有以下代码:

func main() {
initSetLogOutput()

log.Println("Another log")
}

func initSetLogOutput() {
f, err := os.OpenFile("errors.log", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()

log.SetOutput(f)
log.Println("This is a test log entry")
}

编译后,我运行应用程序并获得第一个日志这是一个测试日志条目,但第二个日志没有写入日志文件。是什么原因造成的? log.SetOutput 的声明是否仅限于一个函数的范围?如何让日志输出选项在整个应用程序中持续存在?

我的输出日志如下所示:

2019/01/10 15:53:36 This is a test log entry
2019/01/10 15:54:27 This is a test log entry
2019/01/10 15:55:43 This is a test log entry
2019/01/10 15:57:40 This is a test log entry
2019/01/10 16:02:27 This is a test log entry

最佳答案

initSetLogOutput() 中有一个 defer f.Close() 行,这意味着在 initSetLogOutput() 返回之前,文件将关闭。

而是在 main() 结束时关闭它,像这样:

func main() {
initSetLogOutput()
log.Println("Another log")
closeLogOutput()
}

var logFile *os.File

func initSetLogOutput() {
var err error
logFile, err = os.OpenFile("errors.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}

log.SetOutput(logFile)
log.Println("This is a test log entry")
}

func closeLogOutput() {
logFile.Close()
}

关于go - 将 Golang 日志输出设置为文件不会在函数声明之外持续存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54132579/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com