This is my first attempt to log into files with golang.
file, _ := os.Open("logfile")
log.SetOutput(file)
log.Println("foo")
these lines build, but are not working. Why?
This is my first attempt to log into files with golang.
file, _ := os.Open("logfile")
log.SetOutput(file)
log.Println("foo")
these lines build, but are not working. Why?
Why log.Println(“does not log into file”)?
The reason is because you didn't check the file is exist or not form your code.
file, _ := os.Open("logfile")
you're using _
and didn't check the error. This is important if you wanted to write something in to file. For example look at this code :
f, err := os.OpenFile(filePath+fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
if err != nil {
// if error then you need to create the file first
err = os.MkdirAll(filePath, os.ModePerm)
}
from above code you can see the error checking using if err != nil
. if the file is not exist yet then create the file first. using os.MkdirAll()
.