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 compatiblelog
Standard library: Logrus can be easily replacedlog
Standard 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:
Panic
、Fatal
、Error
、Warn
、Info
、Debug
andTrace
- 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 new
TextFormatter
Structure - Rewrite
Format
Method, add custom color code when formatting logs - Will customize
Formatter
Set 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") }
MyFormatter
The structure has been implementedFormat
method, this method receives aObject, which contains all the information about the log entry, including timestamps, log levels, messages, and fields.
Format
The 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,
Hook
is 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,
Hook
The basic usage involves the following steps: -
Define a Hook structure: This structure needs to be implemented
Levels()
andFire(entry *) error
method. -
accomplish
Levels()
method: This method returns aSlice, indicating which log levels the Hook will be fired.
-
accomplish
Fire(entry \*) error
method: This method defines the logic that should be executed when the log is recorded. -
Add a Hook to a Logrus instance:use
(hook)
method.
CustomizeHook
Example, 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,
MyHook
The structure has been implementedLevels
andFire
method.Levels
The 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.
Fire
The 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.
existmain
In the function, we create a Logrus instance and useAddHook
Methods will be customizedMyHook
Add to Logrus. Afterwards, when we log the log,MyHook
ofFire
The 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!