当前位置:网站首页>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 ")
}
边栏推荐
- 数据湖(十五):Spark与Iceberg整合写操作
- 【补题日记】[2022牛客暑期多校1]J-Serval and Essay
- (6) Decorator extension [email protected] Principle of use
- 攻防世界WEB练习区(weak_auth、simple_php、xff_referer)
- Mysql数据库,查询篇
- Live800: there is nothing trivial about customer service. Don't let service destroy the reputation of the enterprise
- About offline use of SAP Fiori application
- Honey, we are homeless now
- ssm的求职招聘系统兼职应聘求职
- [diary of supplementary questions] [2022 Niuke summer school 1] d-mocha and railgun
猜你喜欢

Programmers can't JVM? Ashes Engineer: all waiting to be eliminated! This is a must skill!

Diversity of SIGIR '22 recommendation system papers

如何获取步态能量图gei

"Why should we do IVX?"—— Interview with IVX CEO Meng Zhiping to understand IVX corporate culture

老公,我们现在无家可归了

ssm的求职招聘系统兼职应聘求职
![[interview: concurrent Article 21: multithreading: activeness] deadlock, livelock, hunger](/img/35/c5f2f8da185d0553c6244d6e4c1216.png)
[interview: concurrent Article 21: multithreading: activeness] deadlock, livelock, hunger

O3DE 的Lumberyard 游戏引擎

Liveqing live broadcast on demand streaming media OBS streaming live broadcast how to obtain interface verification token video verification streamtoken and configure token validity

Unity timeline tutorial
随机推荐
记于2022.7.21
Understand the low code implementation of microservices
[FPGA tutorial case 38] communication case 8 - serial parallel serial data transmission based on FPGA
go strconv
Summary of problems encountered in the development process in July
redis数据类型概念
Skywalking distributed system application performance monitoring tool - upper
go IO操作-文件读
PMP first-hand data and information acquisition
Fasterrcnn sample code test 1: make anchor_ generator = None
NumberOptional:一个字符串转数字的工具
LeetCode-栈和队列刷题
Liveqing live broadcast on demand streaming media OBS streaming live broadcast how to obtain interface verification token video verification streamtoken and configure token validity
Type de symbole
C language actual combat guessing game
AcWing 4499. 画圆 (相似三角形)
[management / upgrade] * 02. View the upgrade path * FortiGate firewall
Attack and defense world web practice area (view_source, get_post, robots)
自定义log注解,请求抓取
Make life full of happiness