How to Log to a File in Go

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!")
}