Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log messages to the console and a file both in golang?

Tags:

go

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?

like image 478
Serge Nikitin Avatar asked Apr 19 '16 13:04

Serge Nikitin


People also ask

How do I log into a file in Golang?

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.

How do I change the log level in Golang?

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.

What is Golang log package?

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.


1 Answers

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) 
like image 83
JimB Avatar answered Sep 19 '22 20:09

JimB