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

标签 go logging

我有以下代码:

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/

相关文章:

macos - 如何在 mac os x 上查找打印机错误日志?

go - 分发 go 可执行文件的有效方法

go - 使资源架构依赖于另一个变量

go - 为什么我无法在 Go 中将指针字符串转换为字符串?

ruby-on-rails - 如何防止记录 Rails 堆栈跟踪

java - 如何在 Selenium WebDriver 中获取 native 记录器

java - 无法阻止 Wildfly 创建日志文件

c++ - 需要知道如何检查输入的字符串是否已在 C++ 中的线程安全记录器内终止

google-app-engine - 在已部署的应用引擎应用程序中,用户 ID 是否可以超过 64 位?

Golang mux 路由器处理程序函数参数