SoFunction
Updated on 2025-04-14

Golang log and logrus example detailed explanation

1. Go standard library log details

1. Functional Features

logIt is a simple log library in the Go language standard library, and its main functions include:

  • Write logs to the specified location (default is standard error)
  • Support logs at _FATAL and _ERROR levels
  • Support formatted log output

2. Common functions

logCommonly used functions in the package are as follows:

Function name Function
Output log
Format output log
Output logs, automatic line wrap
Output log and call (1)
Format the output log and exit
Output log and raise panic
Format the output log and raise panic
Set log format (date, time, etc.)
Set log output target

3. Sample code

package main  
import (  
    "log"  
    "os"  
)  
func main() {  
    // 1. Default output to standard error    ("This is a normal log")  
    // 2. Format output    name := "Alice"  
    age := 30  
    ("User %s is already %d is %d\n", name, age)  
    // 3. Set the log output target to file    file, err := ("", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)  
    if err != nil {  
        (err)  
    }  
    (file)  
    ("Login has been switched to file output")  
    // 4. Set the log format (the default contains time information)    ()  
    //Ldate = 1 << iota // Date of using local time zone: 2009/01/23	//Ltime // Time to use local time zone: 01:23:23	//Lmicroseconds // Microseconds accuracy time: 01:23:23.123123.  Assume Ltime is enabled	//Llongfile // Complete file name and line number: /a/b/c/:23	//Lshortfile // The last part of the file name and line number::23.  Overwrite Llongfile	//LUTC // If Ldate or Ltime is set, UTC is used instead of the local time zone	//Lmsgprefix // Move "prefix" from the beginning of the line to before the message	//LstdFlags = Ldate | Ltime // The initial value of the standard logger, including date and time    ("This is a log containing time")  
    ("Panic\n")
	//("Fatal\n")
}  

4. Advantages and limitations

Advantages

  • Built-in library, easy to use, no additional dependencies required.
  • Supports basic log output and formatting.

Limited

  • The function is relatively simple and does not support multi-log levels (such as DEBUG, INFO, WARNING, etc.).
  • JSON formatted output is not supported.
  • Logrotate is not supported.

2. Third-party library logrus

1. Functional Features

logrusIt is a powerful log library in the Go language, with the main features as follows:

  • Supports multiple log levels:DebugInfoWarningErrorFatalPanic
  • Supports two output formats:textandjson
  • Support log rotation (combinedlumberjackBag)
  • Supports hooks mechanism to extend log processing logic
  • Supports multiple output targets (file, network, console, etc.)

2. Core functions

The following islogrusCore functions:

1. Multi-log level

("Debug log")  
("Information log")  
("Warning Log")  
("Error log")  
("Fatal Error")  
("panic log")  

2. Format output

({  
    "username": "Alice",  
    "age":       30,  
}).Info("User Information")  

3. Switch the output format

// Switch to JSON format(&amp;{})  
//Configure log format to text (default)//(&amp;{})

4. Set log output target

() // Output to standard output  

5. Log rotation (combined with lumberjack)

// Must import(    lumberjack "/natefinch/lumberjack.v2"
)
writer := &amp;{  
    Filename:   "logs/",  
    MaxSize:     500, // MB  
    MaxBackups:  3,  
    MaxAge:      28, // days  
    Compress:   true,  
}  
(writer)  

3. Sample code

Here is a complete onelogrusSample code, including log level, formatting, file rotation and hook functions:

package main  
import (  
    "log"  
    "os"  
    "os/signal"  
    "syscall"  
    "time"  
    lumberjack "/natefinch/lumberjack.v2" 
    "/sirupsen/logrus"  
)  
func main() {  
    // 1. Create a logger instance    logger := ()  
    // 2. Configure log level    ()  
    // 3. Configure the log format to JSON    (&amp;{})  
    // 4. Configure log rotation    writer := &amp;{  
        Filename:   "logs/",  
        MaxSize:     500, // MB  
        MaxBackups:  3,  
        MaxAge:      28, // days  
        Compress:   true,  
    }  
    (writer)  
    // 5. Add hook (Hook)    (&amp;MyHook{})  
    // 6. Write to the log    ("This is an Info-level log")  
    // 7. Log with fields    ({  
        "username": "Bob",  
        "age":      25,  
    }).Error("User not found")  
    // 8. Processing signals    signalChan := make(chan , 1)  
    (signalChan, , )  
    go func() {  
        &lt;-signalChan  
        ("The program has been quit gracefully")  
        (0)  
    }()  
}  
// Custom hook exampletype MyHook struct{}  
func (*MyHook) Levels() [] {  
    return []{  
        ,  
        ,  
    }  
}  
func (*MyHook) Fire(entry *) error {  
    // Hook logic: For example, sending logs to remote server    ("Hook processing: %+v\n", entry)  
    return nil  
}  

4. Advantages and scalability

  • Advantages
    • Powerful, supports multi-log levels and formatting.
    • Highly customizable, supports hook mechanism and multiple output targets.
    • The community has a rich ecology and is widely used in the production environment.
  • Extensibility
    • Supports third-party library extensions (such as log rotation, network output, etc.).

3. Summary

1. When to chooselog

  • When the logging requirements of the project are simple (only basic log output is required).
  • Projects do not want to introduce additional dependencies.

2. When to chooselogrus

  • Projects require multi-log levels and formatted output.
  • Need for higher customizability and scalability.
  • Log rotation and hook mechanisms are required.

3. Comparative summary

characteristic log logrus
Log Level Limited (Fatal, Error) Multi-level (Debug~Panic)
Format output support Support (Text/JSON)
Log rotation Not supported Support (need to cooperate with lumberjack)
Hook mechanism Not supported support
Output target Standard output/file Various (files, networks, etc.)
Community and scalability Built-in library Third-party library, rich community

This is the end of this article about golang log log and logrus. For more related golang log log and logrus content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!