Go: Write log to file

This code appends a log message to the file text.log. It creates the file if it doesn't already exist.

f, err := os.OpenFile("text.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
        log.Println(err)
}
defer f.Close()

logger := log.New(f, "prefix", log.LstdFlags)
logger.Println("text to append")
logger.Println("more text to append")

Contents of text.log:

prefix: 2017/10/20 07:52:58 text to append
prefix: 2017/10/20 07:52:58 more text to append

Comments

Be the first to comment!