我试过几种方法,所有的都失败了。这是我试过的:
func TestLogging(t *testing.T) {
if !FileExists("logfile") {
CreateFile("logfile")
}
f,err := os.Open("logfile")
if err != nil {
t.Fatalf("error: %v",err)
}
// attempt #1
log.Setoutput(io.MultiWriter(os.Stderr,f))
log.Println("hello,logfile")
// attempt #2
log.Setoutput(io.Writer(f))
log.Println("hello,logfile")
// attempt #3
log.Setoutput(f)
log.Println("hello,logfile")
}
func FileExists(name string) bool {
if _,err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func CreateFile(name string) error {
fo,err := os.Create(name)
if err != nil {
return err
}
defer func() {
fo.Close()
}()
return nil
}
日志文件被创建,但没有任何东西被打印或附加到它。为什么?