How do I structure logs with fields using logrus in Go?

Structuring logs with fields in Go using the Logrus logging library is essential for maintaining clarity and organization in your application's logging output. Logrus allows you to enrich logs with structured fields, making it easier to filter and analyze log data later on.

Example of Structuring Logs with Logrus

package main import ( "github.com/sirupsen/logrus" ) func main() { // Create a new logger logger := logrus.New() // Set log level and output format logger.SetLevel(logrus.InfoLevel) logger.SetFormatter(&logrus.TextFormatter{}) // Example of logging with fields logger.WithFields(logrus.Fields{ "username": "testuser", "action": "login", "status": "success", }).Info("User login event") logger.WithFields(logrus.Fields{ "username": "testuser", "action": "fetch_data", "status": "failed", "error": "data not found", }).Error("User fetch data event") }

go logrus structured logging logging in go log fields logging best practices