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
+7.4k Golang : Rot13 and Rot5 algorithms example
+8.1k Golang : HttpRouter multiplexer routing example
+8.9k Golang : Capture text return from exec function example
+4.8k Nginx and PageSpeed build from source CentOS example
+12.6k Golang : Add ASCII art to command line application launching process
+5.9k PHP : Get client IP address
+15.4k Golang : How to convert(cast) IP address to string?
+18.3k Golang : How to get hour, minute, second from time?
+14.9k Golang : How do I get the local IP (non-loopback) address ?
+8.1k Prevent Write failed: Broken pipe problem during ssh session with screen command
+5.1k Golang : Print instead of building pyramids
+13.3k Golang : Increment string example