To write log messages to a file in Go, you can use the standard library's log
package and configure it to output logs to a file. Here's an example:
package main
import (
"log"
"os"
)
func main() {
file, err := os.OpenFile("logs.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
defer file.Close()
log.SetOutput(file)
log.Println("Log message 1")
log.Println("Log message 2")
log.Println("Log message 3")
}
In this example, we open a file logs.txt
in write-only, append mode and set the file as the log output using log.SetOutput(file)
. You can change the log file path or name as per your requirement.
The log messages are written to the file using log.Println()
or log.Printf()
functions. In the given example, we have used log.Println()
to write log messages.
Remember to close the log file after logging is done to flush any remaining log entries. In this example, we have used defer file.Close()
to ensure that file
is closed when the main
function completes.
Note: The log
package provides other functions like log.Printf()
for formatted logging and log.Fatal()
for logging and terminating the program. You can use them as per your requirements.