Often a Go program may need to perform some repetitive writes to a logging file. This could be done directly with IO methods, but the "log" package may be helpful.
With the log module, we can create a new logging object and specify a prefix string
, and various flags that indicate how each line is formatted.
This program creates a file called "test.log
" in the current directory, and it uses the bufio.NewWriter
method to get a writer for the log.New
method.
os.Create
method to create a file. Then with bufio.NewWriter
we get a buffered io.Writer
to use for the log.New
method.log.New
. The second argument is a prefix string
. The third argument is a flag that indicates additional data written.Print()
and Printf()
on the logger instance, we can write formatted strings and other values to the log.bufio.Writer
) so that the log file is written to.package main import ( "fmt" "log" "os" "bufio" ) func main() { // Part 1: get logging file writer set up. file, _ := os.Create("test.log") w := bufio.NewWriter(file) // Part 2: create a new logger with prefix string. logger := log.New(w, "LogPrefix ", log.Ltime) // Part 3: some logging messages. logger.Print("Message One") logger.Print("Message Two"); logger.Printf("Message Three %d", 100) // Part 4: print ending message and flush the bufio to ensure the log data is written. fmt.Println("DONE") w.Flush() }DONELogPrefix 09:46:02 Message One LogPrefix 09:46:02 Message Two LogPrefix 09:46:02 Message Three 100
In the Go standard library, the log module is just additional logic on top of the existing IO types. But this can make logging more uniform and easy to implement.