Introduction to the log of the Go Language Standard Library

1.log

1.1 Use Logger

The log package defines the Logger type, which provides some ways to format the output.
This package also provides a predefined "standard" logger that can be used more easily by calling the Print series (Print|Printf|Println), the Fatal series (Fatal|Fatalf|fatalln), and the Panic series (Panic|Panicf|PanicLn) than by creating a logger object yourself.
For example, like the code below, we can invoke the methods mentioned ashore directly through the log package, which will, by default, expose the log information to the big hidden knife terminal interface.
package main

import (
    "log"
)

func main() {
    log.Println("This is a very common log.")
    v := "Very common"
    log.Printf("This is one%s Journal.\n", v)
    log.Fatalln("This is a trigger fatal Log.")
    log.Panicln("This is a trigger panic Log.")
}

//Result:
2020/02/06 21:57:13 This is a very common log.
2020/02/06 21:57:13 This is a very common log.
2020/02/06 21:57:13 This is a trigger fatal Log.

Process finished with exit code 1
The logger prints the date and time of each log message and defaults to standard errors on the system.
The Fatal series functions call os.Exit(1) after writing log information.
Panic series functions panic after writing log information.

1.2 Configuration logger

Configuration of 1.2.1 standard logger

By default, logger s provide only the time information for the log, but in many cases, we want more information, such as the file name and line number where the log was recorded.
The log standard library provides a way to customize these settings.
The Flags function in the log standard library returns the output configuration of the standard logger, while the SetFlags function is used to set the output configuration of the standard logger.
func Flags() int
func SetFlags(flag int)

flag option

log The Standard Library provides the following flag Options, which are a series of defined constants.
const (
    // Control the details of the output log information, not the order and format of the output.
    // The output log is separated by a colon after each item: for example, 2009/01/2301:23:23.123123/a/b/c/d.go:23: message
    Ldate         = 1 << iota     // Date: 2009/01/23
    Ltime                         // Time: 01:23:23
    Lmicroseconds                 // Time at microsecond level: 01:23:23.123123 (for enhancing Ltime bits)
    Llongfile                     // File full path name + line number: /a/b/c/d.go:23
    Lshortfile                    // Filename + Line Number: d.go:23 (will overwrite Llongfile)
    LUTC                          // Use UTC time
    LstdFlags     = Ldate | Ltime // Initial value of standard logger
)
package main

import (
    "log"
)

func main() {
    //Set logger
    log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate)
    log.Println("This is a very common log.")
}

//Result:
2020/02/06 22:20:40.508109 /Users/tongchao/Desktop/gopath/src/test/test.go:10: This is a very common log.

Process finished with exit code 0

1.2.2 Configure log prefix

log The Standard Library also provides two methods for prefixing log information:
func Prefix() string  //View output prefix of standard logger
func SetPrefix(prefix string)  //Set output prefix
package main

import (
    "log"
)

func main() {
    //Set logger
    log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate)
    log.Println("This is a very common log.")
    log.SetPrefix("[Prefix Information]")
    log.Println("This is a very common log.")
}

//Result:
2020/02/06 22:25:27.654416 /Users/tongchao/Desktop/gopath/src/test/test.go:10: This is a very common log.
[Prefix Information]2020/02/06 22:25:27.654601 /Users/tongchao/Desktop/gopath/src/test/test.go:12: This is a very common log.

Process finished with exit code 0

//This allows the prefix specified in the log information to be added for easy retrieval and processing of the log information later.

1.2.3 Configuration log output location

func SetOutput(w io.Writer)

setOutput Functions are used to set standards logger The default output destination is standard error output.
Export logs to the same directory xx.log File.

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    logFile, err := os.OpenFile("./xx.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.Llongfile | log.Lmicroseconds | log.Ldate)
    log.Println("This is a very common log.")
    log.SetPrefix("[Prefix Information]")
    log.Println("This is a very common log.")
}

//Result:
xx.log Medium content is
2020/02/06 22:30:22.369892 /Users/tongchao/Desktop/gopath/src/test/test.go:17: This is a very common log.
[Prefix Information]2020/02/06 22:30:22.370229 /Users/tongchao/Desktop/gopath/src/test/test.go:19: This is a very common log.
If you want to use standard logger,Write the configuration above to init In function
func init() {
    logFile, err := os.OpenFile("./xx.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.Llongfile | log.Lmicroseconds | log.Ldate)
}

1.3 Create logger

log Creating new ones is also available in the Standard Library logger Object Constructors New,Supporting our own creation logger Example.
New The signature of the function is as follows:
func New(out io.Writer, prefix string, flag int) *Logger
New Create a Logger Object.Where the parameter out Set the destination for writing log information.parameter prefix Will be added before each log generated.parameter flag Define the properties of the log (time, file, and so on).
package main

import (
    "log"
    "os"
)

func main() {
    logger := log.New(os.Stdout, "<New>", log.Lshortfile|log.Ldate|log.Ltime)
    logger.Println("This is customized logger Logs logged.")
}

//Result:
<New>2020/02/06 22:34:17 test.go:10: This is customized logger Logs logged.

Process finished with exit code 0
Gos built-in log libraries have limited functionality to meet different levels of logging. In real projects, we choose third-party log libraries based on our needs, such as logrus--https://github.com/sirupsen/logrus,zap--https://github.com/uber-go/zap, etc.

Tags: Go github

Posted on Thu, 06 Feb 2020 12:42:56 -0500 by andrewgk