Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement idiomatic logging in a Go library?

Tags:

idioms

logging

go

What is an idiomatic way to perform logging in Go?

like image 752
liamzebedee Avatar asked Nov 21 '12 10:11

liamzebedee


People also ask

How do I set up logging in Go language?

The Go standard library has a built-in log package that provides most basic logging features. While it does not have log levels (such as debug, warning, or error), it still provides everything you need to get a basic logging strategy set up. Here's the most basic logging example: package main import "log" func main() { log.Println("Hello world!")

Is it possible to log data in go?

In many cases, regulations such as GDPR and HIPAA may forbid the logging of personal data. The Go standard library has a built-in log package that provides most basic logging features. While it does not have log levels (such as debug, warning, or error), it still provides everything you need to get a basic logging strategy set up.

Should I use the log package or a logging framework?

Using the log package is great for local development when getting fast feedback is more important than generating rich, structured logs. Beyond that, you will mostly likely be better off using a logging framework. A major advantage of using a logging framework is that it helps to standardize the log data.

How do I get Started with logging?

Let’s talk about one standard approach - logging - and how context can help you turn your logs into rich sources of insight. Initially, you might start with the built-in log library, and its Printf interface: This writes to “standard error”. You test this in your program and it works out great for getting the feature working:


1 Answers

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.

like image 134
liamzebedee Avatar answered Nov 16 '22 02:11

liamzebedee