英文:
Golang logger fatal
问题
以下是您提供的代码的翻译:
package main
import (
"bytes"
"fmt"
"log"
)
func main() {
// 将日志输出到字节缓冲区
var buf bytes.Buffer
logInfo := log.New(&buf, "[Info] ", log.Lshortfile)
logInfo.Print("Hello, log file!")
logInfo.Printf("Hello, %s", "crazy")
fmt.Print(&buf)
logInfo.Fatalln("Ut oh")
fmt.Print(&buf)
}
您想要知道为什么logInfo.Fatalln("Ut oh")
没有输出"Ut oh"部分。
英文:
package main
import (
"bytes"
"fmt"
"log"
)
func main() {
// Log into byte
var buf bytes.Buffer
logInfo := log.New(&buf, "[Info] ", log.Lshortfile)
logInfo.Print("Hello, log file!")
logInfo.Printf("Hello, %s", "crazy")
fmt.Print(&buf)
logInfo.Fatalln("Ut oh")
fmt.Print(&buf)
}
Hello. I am trying to use log.Fatal or log.Fatalln instead of having log.New and os.Exit. However, it seems like the logger does not log "Ut oh" part (logInfo.Fatalln)
Following is expected output:
[Info] main.go:17: Hello, log file!
[Info] main.go:18: Hello, crazy
[Info] main.go:17: Hello, log file!
[Info] main.go:18: Hello, crazy
[Info] main.go:xx: Ut oh
Following is what I got:
[Info] main.go:17: Hello, log file!
[Info] main.go:18: Hello, crazy
it seems like it didn't do anything from logInfo.Fatalln("Ut oh")
Could you please tell me what I missed?
Thank you
答案1
得分: 2
log.Fatalln
会终止你的应用程序,所以第二个fmt.Print(&buf)
不会被执行。
将你的日志记录器更改为写入os.Stderr
或其他地方,你将看到Ut oh
被打印出来。
英文:
log.Fatalln
exits your app, so the second fmt.Print(&buf)
does not get executed.
Change your logger to write to os.Stderr
or something and you will see Ut oh
print.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论