Note: Newbie for golang language
Here is the sample program hello.go I wrote to check the behavior and I am seeing the issue where I don't see anything being written by Logger in any functions other than init().
package main
import (
"fmt"
"os"
"io"
"log"
)
var (
testLogger *log.Logger
)
func init() {
test_log := "/tmp/t1.log"
fmt.Printf("Logs are saved to %v
", test_log)
f, err := os.OpenFile(test_log, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
fmt.Printf("ERROR Can't create log file! Reason: %v
", err)
os.Exit(1)
}
defer f.Close()
multiWriter := io.MultiWriter(f)
testLogger = log.New(multiWriter, "", log.Ldate|log.Ltime|log.Lshortfile)
testLogger.Printf("in init..")
}
func main() {
pretest()
test()
testLogger.Printf("Back to main ... ")
}
func pretest() {
testLogger.Printf("In pretest ... ")
}
func test() {
testLogger.Printf("in test..")
}
Here is the output and content of the file being written to:
➜ ./hello
Logs are saved to /tmp/t1.log
➜ cat /tmp/t1.log
2018/06/28 11:23:25 hello.go:27: in init..
AFAIK, The testLogger being shared in the same package should be accessible by each function and able to being used. Please correct me if my understanding is wrong? Am I missing anything in the code? Please provide any pointer or reference on this issue? Thanks.
defer f.Close()
You are doing that defer
in the init
function, meaning that the file will be closed as soon as the init
function finishes.
Since the init
function runs before main
, the file will be closed already when you try to write from all your other functions.
Move that defer
to the main function so that it is closed when your program exits.
Note that in this specific case, you don't even need to close the os.File
since by default File has a finalizer
to close itself when it is collected by the GC (see newFile
function here: https://golang.org/src/os/file_unix.go).