What is an idiomatic way to perform logging in Go?
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!")
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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With