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.
Logrus is a tool that helps your Go program write detailed records of what is happening inside it. Instead of writing plain text lines, it creates structured data (like JSON) that includes specific details like user IDs or error codes alongside the message. This makes it much easier for you to search, filter, and analyze logs when your application runs in production.