Logging in Go using logrus package

Logging is an important task that needs to be done properly when creating large software. It is almost essential in enterprise-level software creation. In this post, we will discuss the logrus package. It’s an external logger package for Golang.

Installing logrus

To install logrus we need to run this command from the terminal:

go get github.com/sirupsen/logrus

This command will install logrus in the package tree.

Logrus Logging examples

Now, we are going to see some examples of the logrus package in action.

1. Logging to the standard output

Logrus helps to log into the standard logger using stdlib log compatible functions as well as enables us to have highly sophisticated output.

package main

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

func main() {
	log.WithFields(log.Fields{
		"user": "admin",
	}).Info("Some interesting info")

	log.Warn("This is a warning")
	log.Error("An error occured!")
}
Logrus Log
Logrus Log

If the tty is enabled, logrus provides colorful output as well.

2. JSON output to the console

We can get JSON output to the std output using JSON formatter. JSON output is helpful when using software that analyses logs and collects valuable info. Also, JSON is a versatile format that is useful in many scenarios.

package main

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

func main() {
        // set json formatter
	log.SetFormatter(&log.JSONFormatter{})
	log.WithFields(log.Fields{
		"user": "admin",
	}).Info("Some interesting info")

	log.Warn("This is a warning")
	log.Error("An error occured!")
}

Now, we will get a JSON output of the logs.

Logrus Log Json
Logrus Log Json

3. Setting log level

We can set the log level before logging so that it will only log to that level or higher.

log.SetLevel(log.WarnLevel)

Now, it will only log to warn level or higher.

4. Creating a new instance

We can create a new instance of logger really easily.

var log = logrus.New()

This allows for modularized logging inside a codebase.

5. Fields with logging

We can have as many fields as we need while logging. These fields are to be specified while logging.

The Withfields function takes fields as key-value pairs.

package main

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

func main() {
	log.WithFields(log.Fields{
		"user":     "admin",
		"password": "pass",
		"key":      "abcd1234",
	}).Info("Hello!")                // time="2020-03-27T09:48:55+05:30" level=info msg="Hello!" key=abcd1234 password=pass user=admin
}

As can be seen, it produces those key-value pairs in the console, alongside the text. It is an extremely helpful feature as it helps to see the log and understand it in a much better way.