Golang logging

From wikinotes

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


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


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



xorm has a really nice logger implementation

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

Sample Implementation

package main

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

var (
    LogDebug *log.Logger
    LogInfo *log.Logger
    LogWarn *log.Logger
    LogError *log.Logger

func setupLog() {
    debug_writer := ioutil.Discard
    info_writer := ioutil.Discard

    for _, arg := range os.Args[1:] {
        switch arg {
        case "-v", "--verbose":
            info_writer = os.Stderr
        case "-vv", "--very-verbose":
            info_writer = os.Stderr
            debug_writer = os.Stderr
    logFmt := log.Ldate|log.Ltime|log.Llongfile

    LogDebug = log.New(debug_writer, "DEBUG: ", logFmt)
    LogInfo = log.New(info_writer, "INFO: ", logFmt)
    LogWarn = log.New(os.Stderr, "WARN: ", logFmt)
    LogError = log.New(os.Stderr, "ERROR: ", logFmt)

func main() {

    LogWarn.Println("high memory usage")
    LogInfo.Println("application started")
    LogDebug.Println("preparing for error...")
    LogError.Println("an error was encountered")

Then on your commandline

go build main.go     # prints            warn/error
go build main.go -v  # prints       info/warn/error
go build main.go -vv # prints debug/info/warn/error