My project has some packages, I don't want to pass log instance from one function to another, instead use a global log instance in there packages.
Here is the demo I have done, but run go run main.go
, nothing print in logs/replica.log.
What's wrong with my code?
├── log
│ └── replica.log
├── logs
│ └── logs.go
├── main.go
$ cat main.go
package main
import (
"./logs"
)
func main() {
logs.Debug("hello")
}
$ cat logs/logs.go
package logs
import (
logging "github.com/op/go-logging"
"os"
)
var log = logging.MustGetLogger("replica")
var format = logging.MustStringFormatter(
`%{time:2006-01-02 15:04:05} [%{level:.4s}] %{shortfile}: %{message}`,
)
func init() {
f, err := os.OpenFile("log/replica.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
defer f.Close()
backend1 := logging.NewLogBackend(f, "", 0)
backend1Formatter := logging.NewBackendFormatter(backend1, format)
logging.SetBackend(backend1Formatter)
}
func Debug(args ...interface{}) {
log.Debug(args)
}
Yes, the defer in logs/logs.go:init() is the issue. Why is that the issue? Let's take a look at the Go Language Spec, specifically the section on Defer statements:
A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function [...] reache[s] the end of its function body [...].
The file is closed when the end of the init function body is reached. Keep in mind, there's no good way to gracefully close a global file.