How to implement idiomatic logging in a Go library?

Create a file that declares a global variable logger. Then, use the idiomatic init() function of Go to initialize the variable on startup.

logger.go:

package xxx

import (
    "log"
    "os"
)

var logger *log.Logger
func init() {
    logger = log.New(os.Stderr, "xxx: ", log.Ldate | log.Ltime | log.Lshortfile)
}

example.go:

func test() {
    logger.Println("Logged")
}

This method offers the benefit that you can use a single logger implementation that can be configured from a single file.

EDIT: ThomasKappler pointed out that if you are only using a single global logger, you can use the log package's inbuilt logger and configure it with SetFlags. The only difference is you must be more explicit and import the log package.

Tags:

Logging

Idioms

Go