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
+15k Golang : Convert an image file to []byte
987 Java : Random alphabets, alpha-numeric or numbers only string generator
+7.7k Golang : Get checkbox or extract multipart form data value example
+4.2k Golang : Random Rune generator
+4.3k Gogland : Where to put source code files in package directory for rookie
+6.6k Golang : Encrypt and decrypt data with x509 crypto
+4.5k Gogland : Single File versus Go Application Run Configurations
+4.7k Yum Error: no such table: packages
+1.9k Golang : How to pass map to html template and access the map's elements
+9.2k Golang : Get current time
+10.2k Golang : GORM create record or insert new record into database example
+24.3k Golang : Get hardware information such as disk, memory and CPU usage