I'm trying to write to a log file with Golang.
I have tried several approaches, all of which have failed. This is what I have tried:
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
}
The log file gets created, but nothing ever gets printed or appended to it. Why?
If you run binary on linux machine you could use shell script.
overwrite into a file
append into a file
overwrite stderr into a file
append stderr into a file
it can be more dynamic using shell script file.
I prefer the simplicity and flexibility of the 12 factor app recommendation for logging. To append to a log file you can use shell redirection. The default logger in Go writes to stderr (2).
See also: http://12factor.net/logs
This works for me
created a package called logger.go
import the package wherever you want to log e.g main.go
I usually print the logs on screen and write into a file as well. Hope this helps someone.
os.Open()
must have worked differently in the past, but this works for me:Based on the Go docs,
os.Open()
can't work forlog.SetOutput
, because it opens the file "for reading:"EDIT
Moved
defer f.Close()
to afterif err != nil
check