英文:
log printf and Write connection
问题
我无法理解为什么在下面的Golang代码中,当你调用底部的write函数时,log.Printf会调用下面的方法:
func write(message string) {
log.Printf("%v\n", message)
}
log.Printf的定义如下:
func (*Logger) Printf
func (l *Logger) Printf(format string, v ...interface{})
以下是完整的代码,请有人解释一下为什么会这样:
package main
import (
"fmt"
stlog "log"
"os"
)
var log *stlog.Logger
type fileLog string
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)
}
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)
}
英文:
I cannot for the life of me from below golang code, why when you call write function at the bottom,
func write(message string) {
log.Printf("%v\n", message)
}
why log.Printf calls below method
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's printf definition is below
func (*Logger) Printf ¶
func (l *Logger) Printf(format string, v ...interface{})
-- Full Code below, someone please explain to me why this is so please--
package main
import (
"fmt"
stlog "log"
"os"
)
var log *stlog.Logger
type fileLog string
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)
}
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
得分: 0
记录器将日志消息写入一个io.Writer
,它是一个定义如下的接口:
type Writer interface {
Write([]byte) (int, error)
}
fileLog
类型实现了io.Writer
接口,并将其设置为新记录器的输出。因此,每当记录器尝试写入日志时,它会调用其写入器的Write
函数,即fileLog.Write
。
英文:
The logger writes the log messages to an io.Writer
, which is an interface defined as:
type Writer interface {
Write([]byte) (int,error)
}
The fileLog
type implements the io.Writer
interface, and you set it as the output of the new logger. So whenever the logger tries to write a log, it calls the Write
function of its writer, which is fileLog.Write
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论