Logging is a very deep subject because different programs have different logging requirements.
fmt.Printf
and fmt.Fprintf
The simplest way to log is to write to standard output (stdout):
fmt.Printf("Logging to %s\\n", "stdout")
To write to standard error (stderr):
fmt.Fprintf(os.Stderr, "Logging to %s\\n", "stderr")
log
packageStandard package [log](<https://golang.org/pkg/log/>)
offers more functionality:
https://codeeval.dev/gist/4257222a6ccfa6b3d3f03b9c1bb1bfb8
Compared to fmt.Printf
, log.Printf
: * by default logs to stderr (os.Stderr
) * adds current time to each log line * ensures that echo log is on it’s own line by adding \\n
if not explicitly provided
To log fatal issues:
f, err := os.Open("file.txt")
if err != nil {
log.Fatalf("os.Open('file.txt') failed with '%s'\\n", err)
}
log.Fatalf
logs the message and calls os.Exit(1)
to end the process.
Log package allows changing where the log output is sent. We can log to a file:
https://codeeval.dev/gist/ed234fc34e1a96fe5aa93f8f975f0da2
When running on Unix, we might log to syslog: