Go:文件中的换行错误日志记录

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

Go: new line in file error logging

问题

我对Go语言相对较新,想要将错误日志记录到一个文本文件中。目前我使用的代码是:

// 日志记录
f, err := os.OpenFile("pgdump_errorlog.txt", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
    log.Fatalf("打开文件时发生错误: %v", err)
}
defer f.Close()
log.SetOutput(f)
//... (稍后的代码)
if err != nil {
  log.Fatal(err)
}

这段代码运行得还可以,只是错误信息没有换行,而是直接追加到第一行的末尾。有没有办法在追加之前让错误信息换行呢?我尝试过:

if err != nil {
     log.Fatalf("\n 错误: %v", err)
}

但是这样根本没有记录日志。我猜想可能需要在某个地方加上"\n",但是我无法弄清楚具体在哪里。

谢谢!

英文:

I am relatively new to go and looking to log out errors to a text file. At the moment I use:

// Logging
f, err := os.OpenFile("pgdump_errorlog.txt", 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)
//... (later on)
if err != nil {
  log.Fatal(err)
}

Which works OK, minus the fact that the errors do not produce a new line and just append to the end of the first line. Is there a way to make the error output create a new line before appending? I've tried:

if err != nil {
     log.Fatalf("\n Error: %v", err)
}

But this didn't log at all. Assuming there needs to be a "\n" somewhere but I am struggling to figure it out.

Thanks

答案1

得分: 2

这是使用回车和换行符在 Fatal 调用之前使用 Print 的情况:

log.Print("\r\n")
//或者 log.Print(err.Error() + "\r\n")
英文:

It was a case of using Print with carriage return and line feed before the Fatal call:

log.Print("\r\n")
//or log.Print(err.Error() + "\r\n")

huangapple
  • 本文由 发表于 2016年1月10日 06:31:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/34699703.html
匿名

发表评论

匿名网友

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

确定