SoFunction
Updated on 2025-03-03

Introduction and usage example code of Golang log library logrus

logrus overview

Introduction

Logrus is a popular Go language log library that provides structured logging and multiple log-level features. Logrus is very flexible and supports custom log formats and outputs, and is widely used by many Go language projects.

Features

Fully compatiblelogStandard library: Logrus can be easily replacedlogStandard library, because it implements the same interface

  • Structured logging: Field data can be easily recorded, which can then be parsed by other log processing systems
  • Multiple log levels:Logrus supports multiple log levels, including:PanicFatalErrorWarnInfoDebugandTrace
  • Easy to integrate: Logrus can be integrated with other systems such as syslog, Hook, etc., which facilitates centralized log management and analysis
  • Highly customizable: The output format and content of the log can be customized through Hooks and formatters

download

go get /sirupsen/logrus

Common methods for logrus

("Debugln")
("Infoln")
("Warnln")
("Errorln")
("Println")
// The output is as followstime="2024-10-20T16:08:01+08:00" level=info msg=Infoln   
time="2024-10-20T16:08:01+08:00" level=warning msg=Warnln
time="2024-10-20T16:08:01+08:00" level=error msg=Errorln 
time="2024-10-20T16:08:01+08:00" level=info msg=Println

debug has no output because the default log output level of logrus is info

Log Level

  • : Log the log and call panic()
  • : Log the log and call (1)
  • : Log error level log
  • : Logging warning level logs
  • : Logs at the information level
  • : Record debug level logs
  • : Logs at the tracking level
package main
import (
	"os"
	"/sirupsen/logrus"
)
func main() {
	// Set log output to	()
	// Set the log level to InfoLevel, which means that logs at InfoLevel and above will be recorded	()
	// Record logs at different levels	("This is a trace message and will not be printed.")
	("This is a debug message and will not be printed.")
	("This is an info message and will be printed.")
	("This is a warning message and will be printed.")
	("This is an error message and will be printed.")
	// Note: PanicLevel and FatalLevel are generally not recommended in production environments because they cause the program to exit.	// ("This is a panic message and will cause the program to panic.")
	// ("This is a fatal message and will cause the program to exit.")
}

Fields

  • WithField(key string, value interface{}) *Entry: Add a field to the log entry
  • WithFields(fields ) *Entry: Add multiple fields to log entries
  • WithError(err error) *Entry: Add error field to log entry
package main
import (
	"os"
	"/sirupsen/logrus"
)
func main() {
	// Set log output to	()
	// Set the log format to JSON, which is useful for structured logging	(&{})
	// Add a field using the WithField method	logEntry := ("user", "Alice")
	// Add multiple fields using the WithFields method	logEntry = ({
		"operation": "login",
		"result":    "success",
	})
	// Record a log containing fields	("User logged in successfully")
	// Use WithError method to add an error field	err := ("something went wrong")
	(err).Error("An error occurred")
}

Output

Log style

Show line number

(true)

Style settings

The default is displayed in the form of text, or can be set to jsong style

textLogger := ()
	// Create a TEXT format logger	(&{
		DisableColors: false,
		FullTimestamp: true,
	})
	// Create a JSON format logger	jsonLogger := ()
	(&{})

Output address

  • SetOutput(): Set the output destination of the log
  • SetFormatter(formatter Formatter): Set the log formatter
package main
import (
	"os"
	"/sirupsen/logrus"
)
func main() {
	// Create a new Logrus instance	log := ()
	// Output to	()
	// Output to file	file, err := ("", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err == nil {
		(file)
	} else {
		("Failed to log to file, using default stderr: %v", err)
	}
	// Output to custom, e.g.	var buffer 
	(&buffer)
	// Record some logs	("This is an info message")
	("This is a warning message")
	("This is an error message")
	// If output to , you can get the log content	logBytes := ()
	(logBytes) // Output the content in the buffer to}

Log color

Default color

  • DebugLevel: Blue
  • InfoLevel: Green
  • WarningLevel: Yellow
  • ErrorLevel: Red
  • FatalLevel: Red (usually accompanied by other instructions, such as exiting the program)
  • PanicLevel: Red (usually accompanied by panic)

Disable color

(&{
	DisableColors: true,
})

Custom colors

  • Create a newTextFormatterStructure
  • RewriteFormatMethod, add custom color code when formatting logs
  • Will customizeFormatterSet to Logrus instance

Custom format

By implementingCustom log format for interface

package main
import (
	"bytes"
	"fmt"
	"/sirupsen/logrus"
	"os"
)
// CustomFormatter Custom Formattertype CustomFormatter struct {
	
}
// Format implementation interfacefunc (f *CustomFormatter) Format(entry *) ([]byte, error) {
	var b *
	if  != nil {
		b = 
	} else {
		b = &{}
	}
	// Add custom color code	color := ""
	switch  {
	case :
		color = "\x1b[34m" // blue	case :
		color = "\x1b[32m" // green	case :
		color = "\x1b[33m" // Yellow	case , , :
		color = "\x1b[31m" // red	}
	// Write color code and log content	(b, "%s%s\x1b[0m\n", color, )
	return (), nil
}
func main() {
	log := ()
	(&CustomFormatter{
		TextFormatter: {
			DisableColors: false,
			FullTimestamp: true,
		},
	})
	("This is a debug message")
	("This is an info message")
	("This is a warning message")
	("This is an error message")
}

MyFormatterThe structure has been implementedFormatmethod, this method receives aObject, which contains all the information about the log entry, including timestamps, log levels, messages, and fields.FormatThe method formats this information into a string and returns a byte array.

[2024-10-20T17:14:22+08:00] [info] A group of walrus emerges from the ocean size=10 animal=walrus 

Hook

  • In Logrus,Hookis an interface that allows you to add custom logic that will be executed before or after logging. By implementingInterface, you can create your own hooks to perform additional operations, such as sending logs to remote systems, writing to databases, performing specific monitoring checks, etc.
  • In Logrus,HookThe basic usage involves the following steps:
  • Define a Hook structure: This structure needs to be implementedLevels()andFire(entry *) errormethod.
  • accomplishLevels()method: This method returns aSlice, indicating which log levels the Hook will be fired.
  • accomplishFire(entry \*) errormethod: This method defines the logic that should be executed when the log is recorded.
  • Add a Hook to a Logrus instance:use(hook)method.

CustomizeHookExample, it prints out the current function name and file name every time the log is logged:

package main
import (
	"fmt"
	"runtime"
	"/sirupsen/logrus"
)
// MyHook is a custom Logrus hooktype MyHook struct {
}
// Levels defines which log levels this hook will be triggeredfunc (hook *MyHook) Levels() [] {
	return 
}
// Fire is a method that is called every time you log infunc (hook *MyHook) Fire(entry *) error {
	// Get the caller's function name and file name	pc, file, line, ok := (8) // 8 is the depth of the call stack, which may need to be adjusted according to your code structure	if !ok {
		("Could not get caller info")
		return nil
	}
	function := (pc).Name()
	("Caller: %s:%d %s\n", file, line, function)
	return nil
}
func main() {
	log := ()
	// Add custom hook	(&MyHook{})
	("This is an informational message")
	("This is a warning message")
}
  • In the above code,MyHookThe structure has been implementedLevelsandFiremethod.LevelsThe method returns a log-level slice, indicating which level of logs this hook will respond to. In this example, we use, which means it will respond to logs at all levels.

FireThe method is called every time the log is logged. In this method, we useTo get the function name and file name of the call logging function and print it out.

existmainIn the function, we create a Logrus instance and useAddHookMethods will be customizedMyHookAdd to Logrus. Afterwards, when we log the log,MyHookofFireThe method will be called and the function name and file name of the call log are printed.

  • Code output:

Caller: D:/goproject/pkg/mod//[email protected]/src/runtime/:272

time="2024-10-20T17:19:37+08:00" level=info msg="This is an informational message"

time="2024-10-20T17:19:37+08:00" level=warning msg="This is a warning message"

Caller: D:/goproject/pkg/mod//[email protected]/src/runtime/:272

This is the article about the introduction and use of Golang logrus. For more information about Golang logrus, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!