Logging is a very deep subject because different programs have different logging requirements.

Logging with 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")

Logging with log package

Standard 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.

Logging to a file

Log package allows changing where the log output is sent. We can log to a file:

https://codeeval.dev/gist/ed234fc34e1a96fe5aa93f8f975f0da2

Logging to syslog

When running on Unix, we might log to syslog:

https://codeeval.dev/gist/86f6bc6fc2186d2fba22a0f5db9128c1