Log to a file in Go by opening a file with os.OpenFile and creating a new logger instance pointing to it.
Use the os package to open a file and log to write to it.
package main
import (
"log"
"os"
)
func main() {
f, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
defer f.Close()
logger := log.New(f, "", 0)
logger.Println("Hello, log file!")
}
Logging to a file in Go creates a text file on your computer and sends your program's messages there instead of just showing them on the screen. Think of it like a diary for your software that records what happened so you can read it later. You use this when you need to keep a permanent record of errors or activity for debugging.