为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕雪6442864 2023-06-01 14:27:16
我有以下代码: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")}编译后,我运行应用程序并获得第一个日志This is a test log entry,但第二个日志未写入日志文件。是什么原因造成的?的声明是否log.SetOutput仅限于函数的范围?如何让日志输出选项在整个应用程序中持续存在?我的输出日志如下所示:2019/01/10 15:53:36 This is a test log entry2019/01/10 15:54:27 This is a test log entry2019/01/10 15:55:43 This is a test log entry2019/01/10 15:57:40 This is a test log entry2019/01/10 16:02:27 This is a test log entry
查看完整描述

1 回答

?
慕斯709654

TA贡献1840条经验 获得超5个赞

里面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()

}


查看完整回答
反对 回复 2023-06-01
  • 1 回答
  • 0 关注
  • 90 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信