我不能從下面的golang代碼中獲得生命,為什么當(dāng)你在底部調(diào)用write函數(shù)時,func write(message string) { log.Printf("%v\n", message)}為什么 log.Printf 調(diào)用下面的方法func (fl fileLog) Write(data []byte) (int, error ) { fmt.Println("does this ever get called?") f, err := os.OpenFile(string(fl), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) if err != nil { return 0, err } defer f.Close() return f.Write(data)}Logger 的 printf 定義如下 func (*Logger) Printf ?func (l *Logger) Printf(format string, v ...interface{})-- 下面是完整代碼,請有人向我解釋一下為什么會這樣--package mainimport ( "fmt" stlog "log" "os")var log *stlog.Loggertype fileLog stringfunc (fl fileLog) Write(data []byte) (int, error ) { fmt.Println("does this ever get called?") f, err := os.OpenFile(string(fl), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) if err != nil { return 0, err } defer f.Close() return f.Write(data)}func registerHandlers() { var msgRaw = "how are you" write(msgRaw)}func run(destination string) { log = stlog.New(fileLog(destination), "", stlog.LstdFlags)}func main() { fmt.Println("here we go") run("../test.log") registerHandlers()}func write(message string) { log.Printf("%v\n", message)}
1 回答

慕容708150
TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個贊
記錄器將日志消息寫入一個io.Writer
,這是一個定義為的接口:
type Writer interface { Write([]byte) (int,error)}
該fileLog
類型實(shí)現(xiàn)了io.Writer
接口,您將其設(shè)置為新記錄器的輸出。因此,每當(dāng)記錄器嘗試寫入日志時,它都會調(diào)用其編寫器的Write
函數(shù),即fileLog.Write
.
- 1 回答
- 0 關(guān)注
- 116 瀏覽
添加回答
舉報
0/150
提交
取消