当前位置:网站首页>Go log package
Go log package
2022-07-24 02:47:00 【go|Python】
List of articles
go log package
log Package introduction
Go Language built in log The package implements a simple log service . This paper introduces the standard library log Basic use of , More convenient and powerful logging needs the help of other third-party log libraries :zap、logrus etc.
log The package defines Logger type , This type provides some ways to format the output
type Logger struct {
mu sync.Mutex // mu Attributes are mainly used to ensure atomic operations
prefix string // prefix Set the prefix of each line
flag int // flag Set various properties of the output , Such as time 、 Line number 、 File path, etc
out io.Writer // out Direction of output , Used to store logs in files
buf []byte // buffer
}
This package also provides a predefined standard logger, By calling the function Print series (Print|Printf|Println)、Fatal series (Fatal|Fatalf|Fatalln)、 and Panic series (Panic|Panicf|Panicln) To use , Create a logger Objects are easier to use
Use Logger
adopt log Package to call the methods mentioned above , By default, the log information will be printed to the terminal interface
func main() {
log.Println(" I'm an ordinary Journal -Println")
log.Printf(" I'm an ordinary Journal :%v-Printf", "lqz")
log.Fatalln(" I am a fatal log -Fatalln")
log.Panicln(" This is a log that triggers an error --Panicln")
}
///fatal A series of functions will be called after writing log information os.Exit(1).Panic The series function will write the log information panic.
Output results
2022/07/22 14:58:19 I'm an ordinary Journal -Println
2022/07/22 14:58:19 I'm an ordinary Journal :lqz-Printf
2022/07/22 14:58:19 I am a fatal log -Fatalln
logger The date of each log message is printed 、 Time , Standard error for default output to system .
logger Configuration of
By default logger Only log time information will be provided , But in many cases we want more information , For example, record the file name and line number of the log .log The standard library provides us with ways to customize these settings .
func Flags() int // Return to standard logger Output configuration for
func SetFlags(flag int) // To set standards logger Output configuration for
flag Parameters
log The standard library provides the following flag Parameters , They are a set of defined constants .
Be careful : You can only control the details of the output log information , Unable to control the order and format of the output , Output logs are separated by a colon after each entry
const (
Ldate = 1 << iota // Local date 00000001
Ltime // Local time 00000010
Lmicroseconds // Microsecond level time , For enhancement Ltime position 00000100
Llongfile // File full pathname + Line number 00001000
Lshortfile // file name + Line number ( Will overwrite Llongfile) 00010000
LUTC // Use UTC Time 00100000
LstdFlags = Ldate | Ltime // standard logger The initial value of the 01000000
)
demonstration
func main() {
fmt.Println(log.Flags()) // Print out 3 It means :Ldate | Ltime Do bit operation to get 00000011
log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate) // Binary system 00001101 Decimal system 13 SetFlags You can pass in binary or decimal numbers , But not recommended , It is more recommended to use well-defined constants
log.Println(" This is a log with file path and date time ")
}
give the result as follows :
3
2022/07/22 14:58:58.338318 D:/goproject/day05/s7.go:19: This is a log with file path and date time
Configure log prefix
log Two methods of prefixing log information are also provided in the standard library :
func Prefix() string // Returns the prefix
func SetPrefix(prefix string) // Set prefix
among Prefix Function to see the standard logger Output prefix for ,SetPrefix Function to set the output prefix .
func main() {
log.SetPrefix(" Order service :")
fmt.Println(log.Prefix())
log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate)
log.Println(" This is a prefixed log ")
}
The output of the above code is as follows :
Order service :
Order service :2022/07/22 14:59:27.719190 D:/goproject/day05/s7.go:25: This is a prefixed log
In this way, we can add the specified prefix to our log information in the code , Convenient retrieval and processing of log information .
Configure log output location
func SetOutput(w io.Writer) // Set standards logger Output destination , Default is standard error output
Output the log to the same directory log.log file
func main() {
logFile,err:=os.OpenFile("./log.log",os.O_CREATE|os.O_WRONLY|os.O_APPEND,0644)
if err != nil {
fmt.Println(" Error opening file :",err)
return
}
log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate)
log.SetPrefix(" Order service :")
log.SetOutput(logFile)
log.Println(" This is a log written into the file --Panicln")
}
The above configuration can be written to init Function
func init() {
logFile,err:=os.OpenFile("./log.log",os.O_CREATE|os.O_WRONLY|os.O_APPEND,0644)
if err != nil {
fmt.Println(" Error opening file :",err)
return
}
log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate)
log.SetPrefix(" Order service :")
log.SetOutput(logFile)
}
establish logger
log The standard library also provides a way to create new logger Object's constructor –New, Support us to create our own 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 . among , Parameters out Set the destination of log information writing . Parameters prefix Will be added in front of each log generated . Parameters flag Define the properties of the log ( Time 、 Documents, etc. ).
for instance :
func main() {
logFile,err:=os.OpenFile("./log.log",os.O_CREATE|os.O_WRONLY|os.O_APPEND,0644)
if err != nil {
fmt.Println(" Error opening file :",err)
return
}
logger:=log.New(logFile," Goods and services :",log.Lshortfile|log.Ldate|log.Ltime)
//logger:=log.New(os.Stdout," Goods and services :",log.Lshortfile|log.Ldate|log.Ltime)
logger.Println(" Log demo case ")
}
give the result as follows :
Goods and services :2022/07/22 14:59:58 s7.go:37: Log demo case
summary : Go Built in log Limited library functions , For example, it can't satisfy the situation of logging at different levels , In the actual project, we choose to use the third-party log library according to our own needs , Such as logrus、zap etc. .
Conventional scheme
In development , The log is usually configured to init Function , Call directly when using log Just go , Write once in a bag init that will do
func init() {
// Automatic execution , No parameters , no return value
log.SetPrefix(" Order service :")
log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate)
logFile,err:=os.OpenFile("./log.log",os.O_CREATE|os.O_WRONLY|os.O_APPEND,0644)
if err != nil {
fmt.Println(" Error opening file :",err)
return
}
log.SetOutput(logFile)
}
func main() {
log.Println(" Output a log ")
}
边栏推荐
- go IO操作-文件写
- Mysql数据库,排序与单行处理函数篇
- Only beautiful ones can be opened
- Custom log annotation, request fetching
- Symbol类型
- Fasterrcnn sample code test 1: make anchor_ generator = None
- Unity TimeLine使用教程
- Uie: unified model of information extraction
- Diversity of SIGIR '22 recommendation system papers
- Nodejs builds cloud native microservice applications based on dapr, a quick start guide from 0 to 1
猜你喜欢

TCP data transmission and performance

Nirvana rebirth! Byte Daniel recommends a large distributed manual, and the Phoenix architecture makes you become a God in fire

Unity TimeLine使用教程

Attack and defense world web practice area (webshell, command_execution, simple_js)

ssm的求职招聘系统兼职应聘求职
[email protected]使用原理"/>(六)装饰器扩展之[email protected]使用原理
![[untitled]](/img/57/916e26018ddfa5ee1ef752fbbc3a4a.png)
[untitled]

Attack and defense world web practice area (view_source, get_post, robots)

攻防世界WEB练习区(backup、cookie、disabled_button)

软考---程序设计语言基础(上)
随机推荐
Zone d'entraînement Web d'attaque et de défense (View source, get Post, robots)
AcWing 4499. 画圆 (相似三角形)
LeetCode-栈和队列刷题
Mysql database, sorting and single line processing functions
C language exercises
Mysql数据库,分组函数篇
X Actual combat - Cloud Server
Understand the low code implementation of microservices
summernote支持自定义视频上传功能
Symbol type
[FPGA tutorial case 39] communication case 9 - interleaving deinterleaving data transmission based on FPGA
【HDLBits 刷题】Verilog Language(2)Vectors 部分
Do securities companies really have principal guaranteed financial products?
UIE: 信息抽取的大一统模型
Data conversion problem in Qt development serial communication software: when reading_ Qbytearray to string; When sending_ Data format; Int to hexadecimal format string; Intercept characters in string
go log包
Understand the timing of loading classes into the JVM
To forge ahead on a new journey, the city chain science and technology carnival was grandly held in Xiamen
[management / upgrade] * 02. View the upgrade path * FortiGate firewall
(6) Decorator extension [email protected] Principle of use