Golang日志记录器致命错误

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

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.

huangapple
  • 本文由 发表于 2015年6月29日 21:04:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/31116503.html
匿名

发表评论

匿名网友

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

确定