Essential Go  Edit on GitHub      File Issue

Logging

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 offers more functionality:

log.Printf("Logging")
log.Printf("Second line\n")
2018/03/09 00:42:35 Logging
2018/03/09 00:42:35 Second line

Compared to fmt.Printf, log.Printf:

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:

logfile, err := os.OpenFile("test.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
	log.Fatalf("os.OpenFile() failed with '%s\n", err)
}
defer logfile.Close()

log.SetOutput(logfile)
log.Println("Log entry")

Logging to syslog

When running on Unix, we might log to syslog:

syslogger, err := syslog.New(syslog.LOG_INFO, "syslog_example")
if err != nil {
	log.Fatalln(err)
}

log.SetOutput(syslogger)
log.Println("Log entry")
  ↑ ↓ to navigate     ↵ to select     Esc to close