Log. 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.
Example. 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.
Part 1 We use the os.Create method to create a file. Then with bufio.NewWriter we get a buffered io.Writer to use for the log.New method.
Part 2 We call log.New. The second argument is a prefix string. The third argument is a flag that indicates additional data written.
Part 3 With Print() and Printf() on the logger instance, we can write formatted strings and other values to the log.
Part 4 It is important to Flush the underlying writer (in this case the 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.