Golang : How to save log messages to file?
Without log file, system administrators and developers life will be difficult or near impossible to do the work. There is no way to tell where and when a fatal error or crash happened. In this short tutorial, we will learn to save direct any log messages generated by your Golang program into a log file.
The code example below will pipe(direct) any log messages generated by log.Println()
functions to the log.txt file.
package main
import (
"log"
"os"
)
func main() {
// make sure log.txt exists first
// use touch command to create if log.txt does not exist
logFile, err := os.OpenFile("log.txt", os.O_WRONLY, 0666)
if err != nil {
panic(err)
}
defer logFile.Close()
// direct all log messages to log.txt
log.SetOutput(logFile)
log.Println("First log message!")
}
Hope this short tutorial can be useful to you. Remember to put to archive old log files with timestamp and roll over to new log file to avoid ending up with super big log file.
See also : Golang : Logging with logrus
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+14k Golang : How to shuffle elements in array or slice?
+9.9k Golang : Embed secret text string into binary(executable) file
+7.2k Android Studio : AlertDialog to get user attention example
+4.1k Golang : Valued expressions and functions example
+5.7k Golang : Detect variable or constant type
+13.6k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+12.7k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+9.1k Golang : How to extract video or image files from html source code
+9.7k Golang : Translate language with language package example
+6.5k Android Studio : Hello World example
+7.2k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image