SoFunction
Updated on 2025-03-03

Golang log library ZAP[uber-go zap] example detailed explanation

golang log library ZAP[uber-go zap]

1. Brief description

zap is an open source Go high-performance log library of uber, which supports different log levels, can print basic information, etc., but does not support log segmentation. Here we can use lumberjack, which is also zap. It is officially recommended for log segmentation. Combining these two libraries, we can implement the following log mechanism:

It can record events into a file instead of the application console; log cutting can cut log files according to file size, time or interval, etc.; supports different log levels, such as DEBUG, INFO, WARN, ERROR, etc.; can print basic information, such as call files, function names and line numbers, log time, etc.; official website address:/uber-go/zap

2. Download and install

// Initialize go mod to manage extension packages through modgo mod init zaplog
//Use the following command to installgo get -u /zap
//If the download fails, use the following command to download and install againgo get /uber-go/zap
//After the download and installation are successful, there are also the following prompts:package /uber-go/zap: code in directory 
src//uber-go/zap expects import "/zap"

3. Configure zap Logger

zap provides two types of loggers—and Logger and Sugared Logger. The difference between the two is:

  • Use Logger in the context where every microsecond and every memory allocation is important. It is even faster than SugaredLogger and has fewer memory allocations, but it only supports strongly typed structured logging.
  • In a context where performance is good but not very critical, use SugaredLogger. It is 4-10 times faster than other structured logging packages and supports structured and printf-style logging.
  • So in general scenarios, we use Sugared Logger.

3.1 Logger

  • Create a Logger by calling()/() or ().
  • Each of the functions above will create a logger. The only difference is that the information it will record is different. For example, production logger records the call function information, date and time by default.
  • Call INFO, ERROR, etc. through Logger.
  • By default, logs are printed to the application's console interface.

3.1.1 NewExample

//Code sample:package main
import (
	"/zap"
)
func main() {
	log := ()
	("this is debug message")
	("this is info message")
	("this is info message with fileds",
		("age", 24), ("agender", "man"))
	("this is warn message")
	("this is error message")
	("this is panic message")
}
//Output result:{"level":"debug","msg":"this is debug message"}
{"level":"info","msg":"this is info message"}
{"level":"info","msg":"this is info message with fileds","age":24,"agender":"man"}
{"level":"warn","msg":"this is warn message"}
{"level":"error","msg":"this is error message"}
{"level":"panic","msg":"this is panic message"}
panic: this is panic message

3.1.2 NewDevelopment

//Code sample:func main() {
	log, _ := ()
	("this is debug message")
	("this is info message")
	("this is info message with fileds",
		("age", 24), ("agender", "man"))
	("this is warn message")
	("this is error message") 
	// ("This is a DPANIC message")	
	// ("this is panic message")
	// ("This is a FATAL message")
}
//Output result:2020-06-12T18:51:11.457+0800	DEBUG	task/:9	this is debug message
2020-06-12T18:51:11.457+0800	INFO	task/:10	this is info message
2020-06-12T18:51:11.457+0800	INFO	task/:11	this is info message with fileds	{"age": 24, "agender": "man"}
2020-06-12T18:51:11.457+0800	WARN	task/:13	this is warn message

	/home/wohu/GoCode/src/task/:13

	/usr/local/go/src/runtime/:200
2020-06-12T18:51:11.457+0800	ERROR	task/:14	this is error message

	/home/wohu/GoCode/src/task/:14

	/usr/local/go/src/runtime/:200

3.1.3 NewProduction

Code Example:
func main() {
	log, _ := ()
	("this is debug message")
	("this is info message")
	("this is info message with fileds",
		("age", 24), ("agender", "man"))
	("this is warn message")
	("this is error message") 
	// ("This is a DPANIC message")	
	// ("this is panic message")
	// ("This is a FATAL message")
}
Output result:
{"level":"info","ts":1591959367.316352,"caller":"task/:10","msg":"this is info message"}
{"level":"info","ts":1591959367.3163702,"caller":"task/:11","msg":"this is info message with fileds","age":24,"agender":"man"}
{"level":"warn","ts":1591959367.3163917,"caller":"task/:13","msg":"this is warn message"}
{"level":"error","ts":1591959367.3163974,"caller":"task/:14","msg":"this is error message","stacktrace":"\n\t/home/wohu/GoCode/src/task/:14\\n\t/usr/local/go/src/runtime/:200"}

3.1.4 Comparative summary

Example and Production use json format output, Development uses line output

  • Development
    • Print up to stack to track
    • Always print packages/files/lines (methods)
    • Add any extra fields at the end of the line as a json string
    • Print level names in capital form
    • Print timestamps in ISO8601 format in milliseconds
  • Production
    • Debug-level messages are not recorded
    • Error , Dpanic level records will track files on the stack, Warn will not
    • Always add the caller to the file
    • Print dates in timestamp format
    • Print level names in lowercase
    • In the above code, we first create a Logger and then log the message using the Logger method such as Info/Error.

The syntax of the logger method is as follows:

func (log *Logger) MethodXXX(msg string, fields ...Field)

Where MethodXXX is a variadic parameter function, which can be Info/Error/Debug/Panic, etc. Each method accepts a message string and any number of long parameters.

Each is actually a set of key-value pair parameters.

3.2 Sugared Logger

The default zap recorder requires structured tags, that is, for each tag, a function of a specific value type is required.

("this is info message with fileds",("age", 24), ("agender", "man"))

Although it will look very long, if the performance requirements are high, this is the fastest choice. You can also use the suger logger, which is based on printf segmentation reflection type detection, providing a simpler syntax to add mixed-type tags.

We use Sugared Logger to achieve the same functionality.

  • Most implementations are basically the same;
  • The only difference is that we get a SugaredLogger by calling the .Sugar() method of the main logger;
  • Then use SugaredLogger to record the statement in printf format;
func main() {
	logger, _ := ()
	slogger := ()
	("debug message age is %d, agender is %s", 19, "man")
	("Info() uses sprint")
	("Infof() uses %s", "sprintf")
	("Infow() allows tags", "name", "Legolas", "type", 1)
}
//Output result:2020-06-12T19:23:54.184+0800	DEBUG	task/:11	debug message age is 19, agender is man
2020-06-12T19:23:54.185+0800	INFO	task/:12	Info() uses sprint
2020-06-12T19:23:54.185+0800	INFO	task/:13	Infof() uses sprintf
2020-06-12T19:23:54.185+0800	INFO	task/:14	Infow() allows tags	{"name": "Legolas", "type": 1}

If needed, you can always switch from sugar logger to standard logger using the .Desugar() method on the logger.

log := ()
("After Desugar; INFO message")
("After Desugar; WARN message")
("After Desugar; ERROR message")

4. Write logs to file

Instead of using a preset method like() to create a logger , we will use the (…) method to pass all configurations manually.

func New(core , options ...Option) *Logger

Three configurations are required - Encoder, WriteSyncer, LogLevel.

Encoder: Encoder (how to write to logs). We will use NewConsoleEncoder() out of the box and pre-set ProductionEncoderConfig() .

(())

WriterSyncer: Specifies where the log will be written. We use the () function and pass the open file handle in.

file, _ := ("./") 
writeSyncer := (file)

Log Level: Which level of log will be written.

// Code example:package main
import (
	"os"
	"/zap"
	"/zap/zapcore"
)
var sugarLogger *
func InitLogger() {
	encoder := getEncoder()
	writeSyncer := getLogWriter()
	core := (encoder, writeSyncer, )
	// () Add the function to log the call function information into the log.	logger := (core, ())
	sugarLogger = ()
}
func getEncoder()  {
	encoderConfig := ()
	 = zapcore.ISO8601TimeEncoder // Modify the time encoder	// Use capital letters to record log levels in log files	 = 
	// NewConsoleEncoder prints more in line with people's observation	return (encoderConfig)
}
func getLogWriter()  {
	file, _ := ("./")
	return (file)
}
func main() {
	InitLogger()
	("this is info message")
	("this is %s, %d", "aaa", 1234)
	("this is error message")
	("this is info message")
}
// Output log file:2020-06-16T09:01:06.192+0800	INFO	task/:40	this is info message
2020-06-16T09:01:06.192+0800	INFO	task/:41	this is aaa, 1234
2020-06-16T09:01:06.192+0800	ERROR	task/:42	this is error message
2020-06-16T09:01:06.192+0800	INFO	task/:43	this is info message

This is the end of this article about the detailed explanation of golang log library ZAP [uber-go zap]. For more related golang log library ZAP content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!