logrus: a log framework of go

Keywords: Go JSON github

summary

Logrus is a log system developed for go language. In this article, we will make a record of some problems encountered in the process of starting logrus. This record refers to This article . Let's start!

Upper hand

package main

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

func main() {
  log.WithFields(log.Fields{
    "animal": "walrus",
  }).Info("A walrus appears")
}

In this way, you can see that the output log format is as follows:

time="2018-08-11T15:42:22+08:00" level=info msg="A walrus appears" animal=walrus

Then the next question is whether the log output in this way can be seen or disorderly. Is there a way to output the log in a more formatted way? We came up with the JSON format. So let's use

log.SetFormatter(&log.JSONFormatter{})

This statement outputs our logs in JSON format:

package main

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

func init() {
	// Set the log format to json format
	log.SetFormatter(&log.JSONFormatter{})

	// Set log output to standard output (default output is stderr, standard error)
	// Log message output can be any io.writer type
	log.SetOutput(os.Stdout)

	// Set log level above warn
	log.SetLevel(log.WarnLevel)
}

func main() {
	log.WithFields(log.Fields{
		"animal": "walrus",
		"size":   10,
	}).Info("A group of walrus emerges from the ocean")

	log.WithFields(log.Fields{
		"omg":    true,
		"number": 122,
	}).Warn("The group's number increased tremendously!")

	log.WithFields(log.Fields{
		"omg":    true,
		"number": 100,
	}).Fatal("The ice breaks!")
}  

The output corresponds to the following:

{"level":"warning","msg":"The group's number increased tremendously!","number":122,"omg":true,"time":"2019-11-13T17:32:42+08:00"}
{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,"time":"2019-11-13T17:32:42+08:00"}  

In addition to setFormatter, which is used to format logs as JSON, we also set the level of displaying logs here.

You can see that each time you add a format of output log after withField, you can output one line of log.

In depth

Sometimes we also need to add information to the log in different parts of the program and output at the end of the program. Here is a way to use the logger:

logger:= log.WithFields(log.Fields{
		"path":       r.URL.Path,
		"method":     r.Method,
		"request_id": reqID,
		"client_ip":  r.RemoteAddr,
		"start_time": startTime,
	})

logger = logger.WithFields(log.Fields{
			"error": err.Error(),
		})

logger.WithFields(log.Fields{
		"error_code": aErr.Code,
		"error_msg":  aErr.Msg,
	}).Warn("FAIL")

As shown in the figure, in this way, you can add the required content to the same log in each part of the program. All we need to do is to use the logger as a parameter to propagate among the functions that need to output the log.

Posted by JamieinNH on Wed, 13 Nov 2019 09:44:26 -0800