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
+25.5k Golang : Detect (OS) Operating System
+19k SSL : How to check if current certificate is sha1 or sha2
+8.5k Golang : ISO8601 Duration Parser example
+14.1k Golang : read gzipped http response
+22.5k Golang : How to read integer value from standard input ?
+6.4k Android Studio : Indicate progression with ProgressBar example
+13.6k Golang : Get IP addresses of a domain name
+7.5k Golang : Format strings to SEO friendly URL example
+8.7k PHP : Convert(cast) bigInt to string
+10.2k Golang : 2 dimensional array example
+35.4k Golang : Comparing date or timestamp
+8.6k Golang : Generate random elements without repetition or duplicate