To log messages with structured data in JSON format using Go, you can make use of the popular logging package called "logrus". Here's how you can do it:
Install logrus
package using go get
command:
go get github.com/sirupsen/logrus
Import logrus
in your Go file:
import (
"github.com/sirupsen/logrus"
)
Customize the log output format to JSON:
func init() {
// Set the log format to JSON
logrus.SetFormatter(&logrus.JSONFormatter{})
}
Create a new log entry and log it with structured data:
log := logrus.WithFields(logrus.Fields{
"user": "john",
"age": 30,
})
log.Info("User login")
In this example, we created a log entry with two structured fields: "user" and "age" using WithFields
method. Then, we logged an info-level message with the structured data using the Info
method.
You can also specify severity levels like Info
, Warning
, Error
, etc., or add additional fields to the log entry as needed.
By default, logrus will output to the standard output (stdout), but you can customize it using different hooks or outputs as per your requirements.