无法将所有日志语句写入文件。

huangapple go评论74阅读模式
英文:

Not able to write all the log statement to the file

问题

我正在尝试为我的代码创建日志文件,但是我无法将所有的日志语句写入文件。

这是我的代码:

func MyLogger() {
    f, err := os.OpenFile("C:\\Project\\GoLang\\src\\Logs\\LogOutput\\TestLog.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")
}
英文:

I am trying to create log file for my code. But I am not able to write all the log statement to the file.

Here's my code:

func MyLogger() {
	f, err := os.OpenFile("C:\\Project\\GoLang\\src\\Logs\\LogOutput\\TestLog.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")
}

答案1

得分: 4

问题在于你在打开日志文件后立即关闭了它。

你调用了log.SetOutput(logFile),但你也调用了defer logFile.Close()defer语句会在MyLogger()函数退出之后立即执行,因此在你实际记录任何内容之前就关闭了文件。

如果你的日志记录器将在整个程序运行期间都保持打开状态,那么你可能根本不需要关闭它,让它在程序退出时自动关闭即可。

如果你确实需要在程序退出之前关闭它,你需要想办法在MyLogger()方法之外存储该文件句柄(也许是在全局变量中,尽管还有其他选项),然后在适当的时候关闭它。

以下是一个完整的示例代码:

package Controllers

import (
    "log"
    "os"
    "io"
)

var logCloser io.Closer

func MyLogger() {
    logFile, err := os.OpenFile("C:/Project/GoLang/src/Logs/log.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
    if err != nil {
        panic(err)
    }
    logCloser = logFile
    log.SetOutput(logFile)
}

func CloseMyLogger() {
    logCloser.Close()
}

请注意,这只是一个示例代码,你可能需要根据你的实际需求进行适当的修改。

英文:

The problem is that you're closing the log file immediately after opening it.

You're calling log.SetOutput(logFile), but you also call defer logFile.Close(). The defer is executed as soon as the function MyLogger() exits--so before you have any chance to actually log anything.

If your logger will run for the entire duration of the program, you probably don't need to close it at all, and let it just get auto-closed when the program exits.

If you do need to close it before the program exits, you'll need to come up with some way to store that file handle outside of the MyLogger() method (perhaps in a global variable, although there are other options), then close it at the appropriate time.

A complete example:

package Controllers

import (
    "log"
    "os"
    "io"
)

var logCloser io.Closer

func MyLogger() {
    logFile, err := os.OpenFile("C:/Project/GoLang/src/Logs/log.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
    if err != nil {
        panic(err)
    }
    logCloser = logFile
    log.SetOutput(logFile)
}

func CloseMyLogger() {
    logCloser.Close()
}

huangapple
  • 本文由 发表于 2017年2月2日 20:07:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/42001859.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定