我试图写一个日志文件与Golang。
我试过几种方法,所有的都失败了。这是我试过的:
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 }
日志文件被创建,但没有任何东西被打印或附加到它。为什么?
os.Open()必须在过去工作不同,但这适用于我:
f,err := os.OpenFile("testlogfile",os.O_RDWR | os.O_CREATE | os.O_APPEND,0666) if err != nil { t.Fatalf("error opening file: %v",err) } defer f.Close() log.SetOutput(f) log.Println("This is a test log entry")
基于Go文档,os.Open()不能用于log.SetOutput
func Open
func Open(name string) (file *File,err error) Open opens the named
file for reading. If successful,methods on the returned file can be
used for reading; the associated file descriptor has mode O_RDONLY. If
there is an error,it will be of type *PathError.
编辑
移动defer f.Close()到后如果err!= nil检查