Location>code7788 >text

Go log management library zap

Popularity:740 ℃/2024-09-19 11:49:00

I. Introduction to zap

In many Go language projects, we need a good logger that can provide the following features:

1. Ability to log events to a file instead of the application console.
2. Log cutting - the ability to cut the log file according to file size, time or interval , etc..
3. Support for different log levels. For example, INFO, DEBUG, ERROR and so on.
4. Ability to print basic information such as call file/function name and line number, log time, etc..

II. Installation and use

2.1 Installation

go get -u /zap

2.2 Configuring the logger logger

Zap provides two types of loggers-Sugared Logger and Logger, generally using Logger .
2.2.1 Initializing the Logger

func InitLogger() *{
	logger ,_ := ()
	
	return logger
}

2.2.2 Initializing SugaredLogger

// call() on top of Logger
func InitLogger() *{
logger ,_ := ()

return ()
}

And the function that initializes the logger call can be called by calling the()/()or()Create a Logger. the difference is that one is returned in json format and the other is returned as terminal standard output with spaces.
NewProducts()
image

NewDevelopment()
image

2.3 Logging with logger

Use logger's own methods for logging, (), (). etc.
The syntax of all these methods is

func (log *Logger) MethodXXX(msg string, fields . .Field)
Example:
(
"msg".
("msg",v), (err), (logger), (logger), (logger), (logger)
(err).

)

Full Code

Click to view code
package main

import (
	"net/http"

	"/zap"
)

var Logger *
func main() {
	//initializationzaplogger
	Logger = InitLogger()
	defer ()
	//Simulation of obligations
	Simplefunc("")
	Simplefunc("")

}
func InitLogger() *{
	logger ,_ := ()
	
	return ()
}

func Simplefunc(url string) {
	res,err:=(url)
	if err!=nil {
		//Recording error logs
		(
			"http get failed..",
			("url:",url),
			(err),
		)
	}else {
		//utilizationinfoRecording Success Logs。
		(
			"get success",
			("status:",),
			("url:",url),
		)
		()
	}
	
	
}

2.4 Customizing the Logger Logger

2.4.1 Writing logs to a file instead of a terminal
The above officially provided logger generation function is not so powerful, the project needs to be logged to the file and split when you need to customize.
zap custom logger generator using ():
func New(core , options ...Option) *Logger
There are three parameters that need to be setEncoder,WriteSyncer,LogLevel
Encoder: The compiler, in layman's terms, is what format the output log is in, json or terminal format.

The json format then uses NewJSONEncoder() with the pre-set ProductionEncoderConfig().
(())
Use NewConsoleEncoder(): (()) for terminal format.
(())

WriteSyncer:Where to output the logs to. Use the()function and passes in the handle of the open file.

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

LogLevel:What level of logging will be output.

Code Example:

Click to view code
//Use a customized zap logger
func InitLogger() *{
//Log file
logfile, _ := ("zap_log.log",os.O_APPEND | os.O_CREATE|os.O_RDWR,0666)
// encoder
encoder := (())
// Output position
writeSyncer := (logfile)

//define core
core := (
encoder,
writeSyncer.
,
)

//create the logger
logger:= (core)

return ()
}

2.4.2 For output to files and terminals, only the WriteSyncer parameter needs to be changed.

Click to view code
//Use a customized zap logger
func InitLogger() *{
//Log file
logfile, _ := ("zap_log.log",os.O_APPEND | os.O_CREATE|os.O_RDWR,0666)
// encoder
encoder := (())
// Output position
// writeSyncer := (logfile)
// Output multiple locations
wc := (logfile,)
writeSyncer := (wc)

// Define core
core := (
writeSyncer, writeSyncer, encoder, writeSyncer, writeSyncer
writeSyncer.
,
)

//create the logger
logger:= (core)

return ()
}

Effect: ! [image](/blog/3452880/202409/)

2.4.3 Converting output to time

// set the log compiler, what type of logs
func getEncoder() {
//encoder configuration
encoderConfig := ()
// Set the time format to 2024-9-1-12.32
= zapcore.ISO8601TimeEncoder
=
// json format
// jsonencoder := (encoderConfig)

// Terminal form
ConsoleEncoder := (encoderConfig)
return ConsoleEncoder

}

2.4.4 Recording different levels of logs
Sometimes the logs can be divided into Record error level logs, and Record success level logs, on full logs.

	core1 := (
		encoder,
		writeSyncer,
		,//complete record
	)
	//error log
	core2 := (
		encoder,
		getwriteSyncer(""),
		,
	)
	c:=(core1,core2)
	logger:= (c,())
	return ()

2.4.5 AddCaller details the lines of code called, AddCallerSkip(1) call chain is a lot of direct skipping

logger:= (core,(), (1))

image

3. Record full logs, error log files, synchronized terminals, standard time, custom logger code for recording code locations

Click to view code
// Use a customized zap logger
func InitLogger() *{

// Encoder
encoder := getEncoder()
// Output location
writeSyncer := getwriteSyncer("log_all.log")

//define core
core1 := (
encoder,
writeSyncer.
,//full record
)
//Error log
core2 := (
encoder,
getwriteSyncer(""), ,
,
)

// Create a single logger
// logger:= (core1, (), (1)) // AddCaller details the line of code called, AddCallerSkip(1) is skipped when there are many calls in the chain.
// return ()

// Create a double log, a full log and an error log.
c:=(core1,core2)
logger:= (c,())
return ()
}

// set the log compiler, what type of logging
func getEncoder() {
//encoder configuration
encoderConfig := ()
// Set the time format to 2024-9-1-12.32
= zapcore.ISO8601TimeEncoder
=
// json format
// jsonencoder := (encoderConfig)

// Terminal form
ConsoleEncoder := (encoderConfig)
return ConsoleEncoder

}

// Set the output location
func getwriteSyncer(logfilename string) {
// logfile
logfile, _ := (logfilename,os.O_APPEND | os.O_CREATE|os.O_RDWR,0666)

// Output to logfile only
// return (logfile)

// Also output to terminal
wc := (logfile,)
return (wc)
}


[========]

[========]

4. Use Lumberjack for log cutting and archiving

// Set the output location
func getwriteSyncer(logfilename string) {
// logfile
// logfile, _ := (logfilename,os.O_APPEND | os.O_CREATE|os.O_RDWR,0666)

// Split the log

l, _ := (
logfilename+". %Y%m%d%H%",
(30*24*), // keep for up to 30 days
(*24), // cut once every 24 hours
)

// Also output to the terminal
wc := (l,)
return (wc)
}

5. Complete code above

Click to view code
package main

import (
"io"
"net/http"
"os"
"time"
rotatelogs "/lestrrat-go/file-rotatelogs"
// "/natefinch/lumberjack.v2"
"/zap"
"/zap/zapcore"
)

var Logger *
func main() {
// Initialize the zap logger
Logger = InitLogger()
defer ()
// simulate the obligation
Simplefunc("")
Simplefunc("")

}
// Use a custom zap logger
func InitLogger() *{

// Encoder
encoder := getEncoder()
// Output location
writeSyncer := getwriteSyncer("log_all")

//define core
core1 := (
encoder,
writeSyncer.
,//full record
)
//Error log
core2 := (
encoder,
getwriteSyncer(""), ,
,
)

// Create a single logger
// logger:= (core1, (), (1)) // AddCaller details the line of code called, AddCallerSkip(1) is skipped when there are many calls in the chain.
// return ()

// Create a double log, a full log and an error log.
c:=(core1,core2)
logger:= (c,())
return ()
}

// set the log compiler, what type of logging
func getEncoder() {
//encoder configuration
encoderConfig := ()
// Set the time format to 2024-9-1-12.32
= zapcore.ISO8601TimeEncoder
=
// json format
// jsonencoder := (encoderConfig)

// Terminal form
ConsoleEncoder := (encoderConfig)
return ConsoleEncoder

}

// Set the output location
func getwriteSyncer(logfilename string) {
// logfile
// logfile, _ := (logfilename,os.O_APPEND | os.O_CREATE|os.O_RDWR,0666)

// Split the log

l, _ := (
logfilename+". %Y%m%d%H%",
(30*24*), // keep for up to 30 days
(*24), // cut once every 24 hours
)

// Also output to the terminal
wc := (l,)
return (wc)
}




func Simplefunc(url string) {
res,err:=(url)
if err!=nil {
// Record the error log
(
"http get failed..." ,
("url:",url),
(err), .
)
}else {
// Use info to log success.
(
"get success",
("status:",), ("url:",)
("url:",url), )
)
()
}


}

Using the zap logger in the gin framework