Mohammad Gholami
20 Jan 2021
•
2 min read
The log package in Golang, allows you to send log messages to log files. This log file can be syslog, mail.log, or your custom log file. In this article, you'll learn how to do this. We are going to use log/syslog package to set the log file.
syslogThe example below shows you the way of sending log messages to /var/log/syslog file in Unix os.
package main import ( "log" "log/syslog" "os" ) func main() { // Log to syslog logWriter, err := syslog.New(syslog.LOG_SYSLOG, "My Awesome App") if err != nil { log.Fatalln("Unable to set logfile:", err.Error()) return } // set the log output log.SetOutput(logWriter) log.Println("This is a log from GOLANG") } Now, if you run the application, This is a log from GOLANG will be logged in the syslog file. You can check it using this command:
$ tail -f /var/log/syslog The output would be something like this:
... Dec 23 01:12:21 sam My Awesome App[102379]: 2020/12/23 01:12:21 This is a log from GOLANG Sometimes you need to log the line number logged message. To do that, you have to set the Lshortfile flag to the log package.
package main import ( "log" "log/syslog" "os" ) func main() { // Log to syslog logWriter, err := syslog.New(syslog.LOG_SYSLOG, "My Awesome App") if err != nil { log.Fatalln("Unable to set logfile:", err.Error()) return } // + set log flag log.SetFlags(log.Lshortfile) // set the log output log.SetOutput(logWriter) log.Println("This is a log from GOLANG") } The logged message would be like this:
Dec 23 01:17:28 sam My Awesome App[103468]: logging.go:20: This is a log from GOLANG As you can see, logging.go:20: is added to the log message and tell you the filename and line number of the code that the log function called.
If you want to write your log messages to a custom log file, take a look at the example below:
package main import ( "log" "log/syslog" "os" ) func main() { // log to custom file LOG_FILE := "/tmp/myapp_log" // open log file logFile, err := os.OpenFile(LOG_FILE, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0644) if err != nil { log.Panic(err) return } defer logFile.Close() // Set log out put and enjoy :) log.SetOutput(logFile) // optional: log date-time, filename, and line number log.SetFlags(log.Lshortfile | log.LstdFlags) log.Println("Logging to custom file") } Now run the application and check the result:
$ tail -f /tmp/myapp_log 2020/12/23 01:29:25 logging.go:29: Logging to custom file These were 2 simple ways to save log messages to log files. I hope you find it helpful.
Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ
108 E 16th Street, New York, NY 10003
Join over 111,000 others and get access to exclusive content, job opportunities and more!