log Go language of the standard library

Whether it is software development debugging phase or the phase of the line after the software logs has always been a very important aspect, we should cultivate the good habit of logging in the program.

log

Go languages built-in logpackage implements a simple log service. This article describes the standard library logbasic use.

Use Logger

log package defines Logger type, which provides a method for the formatting output. This package also provides a pre-defined "standard" logger, by calling the function Print系列(Print | Printf | Println), Fatal系列(Fatal | Fatalf | Fatalln), and Panic系列(Panic | Panicf | Panicln) to use, create a logger than their own objects easier to use.

For example, we may be the same as the following code directly logto invoke methods mentioned above packages, they will default print log information to the terminal interface:

package main

import (
    "log"
)

func main() {
    log.Println("这是一条很普通的日志。")
    v := "很普通的"
    log.Printf("这是一条%s日志。\n", v)
    log.Fatalln("这是一条会触发fatal的日志。")
    log.Panicln("这是一条会触发panic的日志。")
}

Compile and execute the above code output will be as follows:

2017/06/19 14:04:17 这是一条很普通的日志。
2017/06/19 14:04:17 这是一条很普通的日志。
2017/06/19 14:04:17 这是一条会触发fatal的日志。

logger will print the date and time of each log information, the system default output to the standard error. Fatal series of function calls os.Exit after writing log information (1). Panic series function will panic after writing the log information.

Configuration logger

Standard logger configuration

Logger in default only provide time information in the log, but in many cases we want to get more information, such as log file name and line number, etc. of the log. logThe standard library provides a set of methods to customize these for us.

logStandard library Flagsfunction returns a logger standard output configuration, and SetFlagsa function to set the standard output configuration logger.

func Flags() int
func SetFlags(flag int)

flag option

logThe standard library provides the following option flag, which is a series of defined constants.

const (
    // 控制输出日志信息的细节,不能控制输出的顺序和格式。
    // 输出的日志在每一项后会有一个冒号分隔:例如2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
    Ldate         = 1 << iota     // 日期:2009/01/23
    Ltime                         // 时间:01:23:23
    Lmicroseconds                 // 微秒级别的时间:01:23:23.123123(用于增强Ltime位)
    Llongfile                     // 文件全路径名+行号: /a/b/c/d.go:23
    Lshortfile                    // 文件名+行号:d.go:23(会覆盖掉Llongfile)
    LUTC                          // 使用UTC时间
    LstdFlags     = Ldate | Ltime // 标准logger的初始值
)

Let us first before logging set about the standard logger output options are as follows:

func main() {
    log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate)
    log.Println("这是一条很普通的日志。")
}

The output compiled execution are as follows:

2017/06/19 14:05:17.494943 .../log_demo/main.go:11: 这是一条很普通的日志。

Configure log prefix

logThe standard library also provides two ways to log information about prefixes:

func Prefix() string
func SetPrefix(prefix string)

Wherein the Prefixfunction is used to view the standard output logger prefix SetPrefixfunction is used to set the output prefix.

func main() {
    log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate)
    log.Println("这是一条很普通的日志。")
    log.SetPrefix("[小王子]")
    log.Println("这是一条很普通的日志。")
}

The above code is output as follows:

[小王子]2017/06/19 14:05:57.940542 .../log_demo/main.go:13: 这是一条很普通的日志。

So that we can add to our designated prefix log information in the code, after the log information for easy retrieval and processing.

Configuration log output position

func SetOutput(w io.Writer)

SetOutputStandard logger function sets the output destination, the default is the standard error output.

For example, the following code will be output to log in the same directory xx.logfile.

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("这是一条很普通的日志。")
    log.SetPrefix("[小王子]")
    log.Println("这是一条很普通的日志。")
}

If you want to use the standard logger, we will usually write the above configuration operations initfunction.

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)
}

Create a logger

logStandard library also offers to create a new logger object constructor - Newto support the creation of our own logger example. NewSignature function is as follows:

func New(out io.Writer, prefix string, flag int) *Logger

New to create a Logger object. Wherein the parameter setting log information is written out to the destination. Parameters prefix is ​​added to the front of each log produced. Parameters flag custom log attributes (time, files, etc.).

for example:

func main() {
    logger := log.New(os.Stdout, "<New>", log.Lshortfile|log.Ldate|log.Ltime)
    logger.Println("这是自定义的logger记录的日志。")
}

The code is compiled after performing the above, to obtain the following results:

<New>2017/06/19 14:06:51 main.go:34: 这是自定义的logger记录的日志。

to sum up

Go limited built-in log library functions, such as the inability to meet the different levels of log records case, we chose to use a third-party logging library, as according to their needs in the actual project Logrus , ZAP and so on.

Guess you like

Origin www.cnblogs.com/nickchen121/p/11517450.html