How to Use logrus for Structured Logging in Go

Initialize a logrus logger with a JSON formatter and use WithFields to add structured key-value data to your log entries.

Use the github.com/sirupsen/logrus package to create a logger that outputs structured JSON or text logs with key-value pairs.

package main

import (
	"github.com/sirupsen/logrus"
)

func main() {
	log := logrus.New()
	log.SetFormatter(&logrus.JSONFormatter{})
	log.SetLevel(logrus.InfoLevel)

	log.WithFields(logrus.Fields{
		"user_id": 123,
		"action":  "login",
	}).Info("User logged in")
}

Install the package first with go get github.com/sirupsen/logrus.