donljt2606 2019-01-10 16:04
浏览 57
已采纳

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

I have the following code:

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")
}

After compilation I run the application and I get the the first log This is a test log entry but the second log does not write to the log file. What is causing this? Is the declaration of log.SetOutput limited to the scope of a function? How do I get the log output option to persist throughout the entire application?

My output log looks like below:

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
  • 写回答

1条回答 默认 最新

  • dongyi5425 2019-01-10 16:07
    关注

    Inside initSetLogOutput() you have a defer f.Close() line, which means before initSetLogOutput() returns, the file will be closed.

    Instead close it at the end of main(), like this:

    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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于RTKLIB框架写的精密单点定位-AR
  • ¥15 PFENet的预训练权重
  • ¥15 程序哪有错误怎么改?
  • ¥15 交换机和交换机之间的链路带宽以及主机带宽的理解
  • ¥15 ai创想家对战模式代码
  • ¥15 集合A由3个2行4列二维数组构成,从集合A中任意取一个二维数组元素、如果该二维数组元素的对应列位置的上、下两数都是奇数,而且仅有2个列是奇数/奇数,则该数组有意义,并放入集合B中打印输出。
  • ¥15 电信IPV6 无法外网访问吗
  • ¥15 有偿求效果比较好的遥感影像匹配的c++代码
  • ¥15 博主,你好,我下载了你的智能网联汽车辅助驾驶安全信息检测系统,现在不会运行,可以教我吗,
  • ¥15 怎么在excle输入下列公式