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 ( "This is a very common log.")
	v: = "very common"
	log.Printf ( "this is a log% s. \ n", v)
	log.Fatalln ( "This is a trigger fatal logs.")
	log.Panicln ( "This is a trigger panic log.")
}

  

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

2017/06/19 14:04:17 This is a very common log.
2017/06/19 14:04:17 This is a very common log.
2017/06/19 14:04:17 This is a trigger fatal logs.

  

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 at the time by default will only provide information on 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 (
    // log information output control details, order and format of the output can not be controlled.
    // log output will be separated by a colon after each one: for example, 2009/01/23 01: 23: 23.123123 /a/b/c/d.go:23: message
    Ldate = 1 << iota // Date: 2009/01/23
    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 // filename + line number: d.go: 23 (will overwrite Llongfile)
    LUTC // use UTC time
    LstdFlags = Ldate | Ltime // initial value of the standard 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 ( "This is a very common log.")
}

  

The output compiled execution are as follows:

2017/06/19 14: 05: 17.494943 ... / log_demo / main.go: 11: This is a very common log.

 

Configure log prefix

logStandard library also provides information on the log information prefixes two methods:

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 ( "This is a very common log.")
	log.SetPrefix ( "[Prince]")
	log.Println ( "This is a very common log.")
}

  

The above code is output as follows:

[Prince] 2017/06/19 14: 05: 57.940542 ... / log_demo / main.go: 13: This is a very common log.

  

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 ( "This is a very common log.")
	log.SetPrefix ( "[Prince]")
	log.Println ( "This is a very common log.")
}

  

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 ( "This is a log custom logger records.")
}

  

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

<New> 2017/06/19 14:06:51 main.go: 34: this is a custom logger log record.

  

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.