os.Open()
must have worked differently in the past, but this works for me:
f, err := os.OpenFile("testlogfile", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
log.SetOutput(f)
log.Println("This is a test log entry")
Based on the Go docs, os.Open()
can’t work for log.SetOutput
, because it opens the file “for reading:”
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 modeO_RDONLY
. If
there is an error, it will be of type*PathError
.
EDIT
Moved defer f.Close()
to after if err != nil
check