The standard library of Go language provides a simple log package. It not only provides many functions, but also defines a type Logger containing many methods. The Logger will print the date and time of each log information. The default output is standard error. The Fatal series function will call os. after writing log information. Exit(1). The panic series of functions will panic after the log information is written. The basic usage of the standard library log is described in detail below.
function
The log package of Golang mainly provides the following functions with output functions:
func Fatal(v ...interface{}) func Fatalf(format string, v ...interface{}) func Fatalln(v ...interface{}) func Panic(v ...interface{}) func Panicf(format string, v ...interface{}) func Panicln(v ...interface{}) func Print(v ...interface{}) func Printf(format string, v ...interface{}) func Println(v ...interface{})
Example
//l.Output(2, fmt.Sprintf(format, v...)) v := "ordinary" log.Printf("One%s journal.\n", v) //l.Output(2, fmt.Sprintln(v...)) log.Println("An ordinary log.") //l.Output(2, fmt.Sprintln(v...)) //os.Exit(1) log.Fatalln("One trigger fatal Log of.") //s := fmt.Sprintln(v...) //l.Output(2, s) //panic(s) log.Panicln("One trigger panic Log of.")
Operation results
021/12/22 15:01:01 A normal log. 2021/12/22 15:01:01 A normal log. 2021/12/22 15:01:01 One trigger fatal Log of.
The above functions are used in exactly the same way as the fmt package. The specific fmt package has been introduced in the previous article, >>Portal . By viewing the source code, you can find:
- log.Fatal [ln|f] is actually a call to OS after Printf [ln|f] is called Exit (1) exit the program.
- log.Panic [ln|f] is actually called Printf [ln|f], and then the panic() function is called to throw a panic.
- Print[ln|f] is actually the called Output() function.
Source code of function Output():
func (l *Logger) Output(calldepth int, s string) error { now := time.Now() // get this early. var file string var line int l.mu.Lock() defer l.mu.Unlock() if l.flag&(Lshortfile|Llongfile) != 0 { // Release lock while getting caller info - it's expensive. l.mu.Unlock() var ok bool _, file, line, ok = runtime.Caller(calldepth) if !ok { file = "???" line = 0 } l.mu.Lock() } l.buf = l.buf[:0] l.formatHeader(&l.buf, now, file, line) l.buf = append(l.buf, s...) if len(s) == 0 || s[len(s)-1] != '\n' { l.buf = append(l.buf, '\n') } _, err := l.out.Write(l.buf) return err }
It can be found that:
- The function uses a mutex to ensure the security of multiple goroutine s writing logs, and when calling runtime Before caller (), the mutex lock is released first, and then the lock is added after obtaining the information to ensure security.
- Use the formataheader() function to format the log information, then save it to buf, and then append the log information to the end of buf. Then judge whether the log is empty or the end is not \ n. if so, append \ n to the end of buf, and finally output the log information.
Configure logger
By default, the logger only provides log time information, and the log standard library also provides some customized methods. You can get more information, such as the file name and line number of the log.
Flags
The Flags function in the log standard library returns the output configuration of the standard logger, and the SetFlags function is used to set the output configuration of the standard logger.
func Flags() int func SetFlags(flag int)
The log standard library provides the following flag options, which are a series of defined constants.
const ( // Controls the details of the output log information, not the order and format of the output. // The output log will be separated by a colon after each item: for example, 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message Ldate = 1 << iota // Date: January 23, 2009 Ltime // Time: 01:23:23 Lmicroseconds // Microsecond time: 01:23:23.123123 (used to enhance Ltime bit) Llongfile // File full path name + line number: / a/b/c/d.go:23 Lshortfile // File name + line number: d.go:23 (Llongfile will be overwritten) LUTC // Use UTC time LstdFlags = Ldate | Ltime // Initial value of standard logger )
Example
func main() { log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate) log.Println("A very common log.") } //output //2021/12/22 15:09:08.290930 /box/main.go:7: a very common log.
Log Prefix
The Prefix function is used to view the output Prefix of the standard logger, and the SetPrefix function is used to set the output Prefix.
func Prefix() string func SetPrefix(prefix string)
Example
func main() { log.SetPrefix("[info]") log.Println("An ordinary log") fmt.Println(log.Prefix()) } //output //[info]2021/12/22 15:15:28 an ordinary log //[info]
Output position output
The SetOutput function is used to set the output destination of the standard logger. The default is standard error output.
func SetOutput(w io.Writer)
Example
func main() { logFile, err := os.OpenFile("./test.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) if err != nil { fmt.Println("open log file failed, err:", err) return } log.SetOutput(logFile) log.SetFlags(log.Lshortfile | log.Lmicroseconds | log.Ldate) log.SetPrefix("[info]") log.Println("A very common log") }

Custom logger
The lo g standard library also provides a New constructor to create a New logger object, which enables us to create our own logger.
func New(out io.Writer, prefix string, flag int) *Logger { return &Logger{out: out, prefix: prefix, flag: flag} }
- New creates a Logger object
- Parameter out sets the destination of log information writing
- The parameter prefix log prefix will be added in front of each generated log
- The parameter flag defines the attributes of the log (time, file, etc.)
Example
func main() { logger := log.New(os.Stdout, "<info>", log.Lshortfile|log.Lmicroseconds|log.Ldate) logger.Println("Custom logger journal") } //output //<info>2021/12/22 23:30:16.283401 main. Go: 10: Custom logger log
Due to the limited functions of the built-in log Library of go, you can choose to use the third-party log library according to your needs in the actual project, such as logrus, zap, etc.
Pictures and some relevant technical knowledge points come from network search, infringement deletion!
reference material:
https://www.jianshu.com/p/66c75589d6b5
https://www.cnblogs.com/flippedxyy/p/15558771.html