Logging

suggest change

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")
2020/07/12 07:24:09 Logging
2020/07/12 07:24:09 Second line

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:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents