How to log messages with structured data (e.g., JSON) in Go?

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:

  1. Install logrus package using go get command:

    go get github.com/sirupsen/logrus
  2. Import logrus in your Go file:

    import ( "github.com/sirupsen/logrus" )
  3. Customize the log output format to JSON:

    func init() { // Set the log format to JSON logrus.SetFormatter(&logrus.JSONFormatter{}) }
  4. 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.

  5. 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.