Golang logging

From wikinotes

Logging is a standardized format of writing progress/debug info.

Documentation

log https://pkg.go.dev/log
logfmt flags https://pkg.go.dev/log#pkg-constants

Basics

Go creates a logger that logs to stderr by default.
If you like, you can modify it's logformat.
There are no log-levels by default.

// customize default log's logformat
log.SetFlags(log.Ldate|log.Ltime|log.Llongfile)

// log methods similar to 'fmt.*' methods
log.Println("application started")  // log message
log.Fatalln("application exiting")  // os.Exit(1) after logged
log.Panicln("application panicked") // panic() after logged

LogLevels

Go doesn't provide log-levels, but you can create separate loggers to implement this yourself.
You don't need to do this in every file, log-format flags indicating filepath will use the correct path where it is called from.

import "os"
import "io/ioutil"
import "log"

logFmt := log.Ldate|log.Ltime|log.Llongfile

InfoLogger := log.New(os.Stderr, "INFO: ", logFmt)
ErrorLogger := log.New(os.Stderr, "ERROR: ", logFmt)
DebugLogger := log.New(ioutil.Discard, "DEBUG: ", logFmt)  // redirects to /dev/null

Template:Example