I am writing an application in which i need to record logs in two different files. For Example weblogs.go and debuglogs.go. I tried using the log4go but my requirement is i need the logger to be created in main file and be accessible in sub directory as major of decoding and logging is done in sub file. Can anybody please help with that?
Here's one way to do it, using the standard log
package:
package main
import (
"io"
"log"
"os"
)
func main() {
f1, err := os.Create("/tmp/file1")
if err != nil {
panic(err)
}
defer f1.Close()
f2, err := os.Create("/tmp/file2")
if err != nil {
panic(err)
}
defer f2.Close()
w := io.MultiWriter(os.Stdout, f1, f2)
logger := log.New(w, "logger", log.LstdFlags)
myfunc(logger)
}
func myfunc(logger *log.Logger) {
logger.Print("Hello, log file!!")
}
Notes:
io.MultiWriter
is used to combine several writers together. Here, it creates a writer w
- a write to w
will go to os.Stdout
as well as two fileslog.New
lets us create a new log.Logger
object with a custom writerlog.Logger
object can be passed around to functions and used by them to log thingsIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With