To create a log in Golang, you can use the built-in “log” library. The package log in Go implements the simple logging package that defines a type, Logger, with methods for formatting output.
You can use these rough-and-ready logs for local development in which you need to get fast feedback from your code may be more important than generating rich, structured logs.
To generate rich and structured logs, third-party packages will be more helpful.
Example
For example, you can define the division function that returns the error to the caller rather than exiting the program when you attempt to divide by zero.
package main
import (
"errors"
"fmt"
"log"
)
func division(x float32, y float32) (float32, error) {
if y == 0 {
return 0, errors.New("can't divide by zero")
}
return x / y, nil
}
func main() {
var x float32 = 11
var y float32
res, err := division(x, y)
if err != nil {
log.Print(err)
}
fmt.Println(res)
}
Output
2019/11/28 18:50:19 can't divide by zero
0
In the above program, we have imported three packages.
- errors
- fmt
- log
Then we have defined a function division(), which accepts two parameters.
We are checking the dividing by 0 error; if it occurs, we log that error in the console.
If we meet the divide by 0 conditions, one error will be generated, and then we log that error in the console and print the return value.
In the above program, we got the divide by 0 conditions; that is why we got the output log.
go get github.com/Sirupsen/logrus
Example
package main
import (
log "github.com/sirupsen/logrus"
)
func main() {
log.WithFields(log.Fields{
"Best Song": "Sunflower",
}).Info("One of the best song")
}
Output
Note that it’s utterly API-compatible with the stdlib logger so that you can replace your log imports everywhere with log “github.com/sirupsen/logrus“, and you’ll now have the flexibility of Logrus. You can customize it all you want.
Best practices for writing and storing Golang logs
The first thing while writing a log is to find a perfect library. Then after you have chosen the logging library, you’ll also want to plan for where in your code to make calls to the logger, how to store your logs, make them available at any given time, and analyze them.
Let’s see some of the best practices.
- You can call the logger from within your primary application process, not within the goroutines.
- It is considered good practice to write logs from your application to a local file, even if you will ship them to a central platform later.
- You can standardize your logs with a set of predefined messages.
- You can send your logs to the central platform to analyze and aggregate them.
- Use the HTTP headers and unique IDs to log user behavior across microservices.
That’s it.