I can direct all messages to log.txt
file:
logFile, err := os.OpenFile("log.txt", os.O_CREATE | os.O_APPEND | os.O_RDWR, 0666) if err != nil { panic(err) } log.SetOutput(logFile)
But how can I get log messages in console too?
To log to a file, you can use the OS package to create a log file if it does not exist or open and write to an existing file. Doing so will set the output of the log package to the specified output file. Keep in mind that the log package also supports other output destination that supports io.
To use the level package, create a logger as per normal in your func main, and wrap it with level. NewFilter. Then, at the callsites, use one of the level. Debug, Info, Warn, or Error helper methods to emit leveled log events.
Package log implements a simple logging package. It defines a type, Logger, with methods for formatting output. It also has a predefined 'standard' Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and Panic[f|ln], which are easier to use than creating a Logger manually.
Use an io.MultiWriter
MultiWriter creates a writer that duplicates its writes to all the provided writers, similar to the Unix tee(1) command
logFile, err := os.OpenFile("log.txt", os.O_CREATE | os.O_APPEND | os.O_RDWR, 0666) if err != nil { panic(err) } mw := io.MultiWriter(os.Stdout, logFile) log.SetOutput(mw)
The only change was
mw := io.MultiWriter(os.Stdout, logFile)
If 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